sorting char arrays...
hi there,
Im working on this question:
write a program which will read a string and rewrite it alphabetical order. For example, the word STRING should be written as GINRST.
i have done the following:
publicstaticvoid main(String[]args){
InputStreamReader tr =new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(tr);
String s;
try{
System.out.println("Enter Text");
s = br.readLine();
char[] chars = s.toCharArray(); [size="3"][size="2"][size="1"]//Convert the string to array of characters using [/size][/size][/size]
/* Sort the char[] goes somewhere here...*/
s =new String(chars);//Convert the char[] back to string using
Im having problems with the sorting part, I really hope 2 get some help with it.
thanks,
trying2learn
Hi,
Thanks for the help.
I just have one stupid error, here's the code that i did:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Que{
public static void main(String[]args)
{
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
String s;
try{
System.out.println("Enter text");
s = br.readLine();
char[] chars = s.toCharArray();
String s1 = "SORT";
char ch[] = s.toCharArray();
s1.sort(ch);
for(int i=0; i<ch.length; i++) System.out.print(ch[i]);
s = new String (chars);
//.out.println("the String in alphabetical order is: " sort());
}
catch (Exception e){
e.printStackTrace();
}
}
}
I hope that someone can help me debug this error,
thanks!
liveurlife>
char[] chars = s.toCharArray(); //Why to declare two char arrays? You can avoid one
String s1 = "SORT"; // If you are getting the string from console then use that string. No need to declare one more string
char ch[] = s.toCharArray();
s1.sort(ch); // There is no sort() method in String class. sort method is there only in Array class - "java.util.Arrays.sort(ch)"
hey,
Thanks, 4 helping me out i finally understood it.......thank you.
here is the correct code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Que3{
public static void main(String[]args)
{
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
String s;
try{
System.out.println("Enter text");
s = br.readLine();
char ch[] = s.toCharArray();
java.util.Arrays.sort(ch);
for(int i=0; i<ch.length; i++) System.out.print(ch[i]);
s = new String (ch);
}
catch (Exception e){
e.printStackTrace();
}
}
}
take care and thanks once again!>