简体   繁体   中英

single string list- alphabetizing

I'm trying to write a code that uses a scanner to input a list of words, all in one string, then alphabetizer each individual word. What I'm getting is just the first word alphabetized by letter, how can i fix this?

the code:

else if(answer.equals("new"))
    {
      System.out.println("Enter words, separated by commas and spaces.");
      String input= scanner.next();
      char[] words= input.toCharArray(); 
      Arrays.sort(words);
      String sorted= new String(words);
      System.out.println(sorted);

    }

Result: " ,ahy "

You're reading in a String via scanner.next() and then breaking that String up into characters. So, as you said, it's sorting the single-string by characters via input.toCharArray() . What you need to do is read in all of the words and add them to a String [] . After all of the words have been added, use Arrays.sort(yourStringArray) to sort them. See comments for answers to your following questions.

You'll need to split your string into words instead of characters. One option is using String.split . Afterwards, you can join those words back into a single string:

System.out.println("Enter words, separated by commas and spaces.");
String input = scanner.nextLine();

String[] words = input.split(",| ");
Arrays.sort(words);

StringBuilder sb = new StringBuilder();
sb.append(words[0]);
for (int i = 1; i < words.length; i++) {
    sb.append(" ");
    sb.append(words[i]);
}
String sorted = sb.toString();

System.out.println(sorted);

Note that by default, capital letters are sorted before lowercase. If that's a problem, see this question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM