You are given a String text. Determine the letters (both lowercase and uppercase) that appear in text. Return a String which contains those letters, converted to lowercase, and then sorted in alphabetical order. The returned String should include all occurrences of each letter.
Definition
Class:
TextProcessor
Method:
collectLetters
Parameters:
String
Returns:
String
Method signature:
String collectLetters(String text)
(be sure your method is public)
Constraints
-
text will contain between 1 and 50 characters, inclusive.
-
text will contain only letters ('A'-'Z', 'a'-'z'), digits ('0'-'9'), and spaces (' ').
Examples
0)
"She sells sea shells"
Returns: "aeeeehhllllssssss"
The letters that appear in the input are "shesellsseashells" (converted to lower case and ignoring non-letter characters). Then we sort these letters alphabetically.
1)
"ReMemBEr To IgnoRE CASe"
Returns: "abceeeeegimmnoorrrst"
2)
"12345"
Returns: ""
There are no letters, so the empty String should be returned.
3)
"TopCoder is fun"
Returns: "cdefinooprstu"
4)
"Knights are better than Bishops"
Returns: "aabbeeeghhhiiknnoprrssstttt"
import java.util.*;
public class TextProcessor {
public static String collectLetters(String text) {
List<Character> list = new ArrayList<Character>();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (Character.isLetter(ch)) {
if (Character.isUpperCase(ch))
ch = (char) (ch - 'A' + 'a');
list.add(ch);
}
}
Collections.sort(list);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++)
sb.append(list.get(i));
return sb.toString();
}
}