Results 1 to 2 of 2
- 05-11-2012, 10:44 PM #1
Member
- Join Date
- May 2012
- Posts
- 4
- Rep Power
- 0
Help - (Sorting characters in a string)
Hi all, first of all I would like to thank you for all the help :) hopefully someday soon I'll be able to help people here as well.
I need to write a program doing this:
(Sorting characters in a string) Write a method that returns a sorted string using the following header:
public static String sort(String s) For example, sort("acb") returns abc.
Write a test program that prompts the user to enter a string and displays the sorted string.
Here's the code I wrote and I have a questions: (don't mind the class name)
I can't figure out how to do the part of sorting the letters...Java Code:import java.util.Scanner; public class copy { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Please enter a string"); String str = input.next(); System.out.println("The sorted string is: " + sort(str)); } public static String sort (String str) { StringBuilder newStr = new StringBuilder(str); //create a String Builder for (int i = 0; i < newStr.length(); i++) { if (Character.isLetter(newStr.charAt(i))) //if is letter then check which is bigger { } } for (int i = 0; i < newStr.length(); i++) //eliminate != letters { if (Character.isLetter(newStr.charAt(i)) == false) { newStr.deleteCharAt(i); i--; } } //end of eliminate != letters str = newStr.toString(); //convert StringBuilder to String return str; } }
Would love to get some help :)Java Code:for (int i = 0; i < newStr.length(); i++) { if (Character.isLetter(newStr.charAt(i))) //if is letter then check which is bigger { } }
Cheers,
Dan
- 05-11-2012, 11:57 PM #2
Re: Help - (Sorting characters in a string)
read all characters into an array of char and than use Arrays.sort(yourCharArray)
Similar Threads
-
Reading characters into a string
By Teclis in forum New To JavaReplies: 2Last Post: 03-08-2011, 10:08 PM -
Swap characters in a string.
By Sdannenberg3 in forum New To JavaReplies: 4Last Post: 03-04-2010, 08:49 PM -
deleting characters from a String
By Hayzam in forum New To JavaReplies: 4Last Post: 08-29-2008, 12:14 PM -
how to get the characters one by one from a String?
By Somitesh Chakraborty in forum New To JavaReplies: 3Last Post: 08-20-2008, 08:56 PM -
Getting all characters in a String
By Alayna in forum New To JavaReplies: 2Last Post: 05-20-2007, 11:49 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks