There are several ways to map letters to number. If you want a simple mapping, a:1,b:2,...,i:9,j:10,...,z:26
you can do the following, and take advantage of the fact chars map to ints:
StringBuilder sb= new StringBuilder();
for (char letter : phoneWord.toLowerCase().toCharArray()) {
sb.append((int) letter - 96);
}
System.out.println(sb.toString());
You can add a modulus to keep the numbers between 0 and 9 with %10
this will map a:1,b:2,...,i:9,j:0,...,z:6
sb = new StringBuilder();
for (char letter : phoneWord.toLowerCase().toCharArray()) {
sb.append(((int) letter - 96) % 10);
}
System.out.println(sb.toString());
If you want a custom mapping, such as that of a phone you can create a map like so:
Map<Character, Integer> letterMap = new HashMap<>();
letterMap.put('a', 1);
letterMap.put('b', 1);
letterMap.put('c', 1);
letterMap.put('d', 2);
// ...
letterMap.put('z', 9);
sb = new StringBuilder();
for (char letter : phoneWord.toLowerCase().toCharArray()) {
sb.append(letterMap.get(letter));
}
System.out.println(sb.toString());
I am using .toLowerCase()
on the string to reduce the number of letters that need to be mapped. As (int) 'A' = 65
and (int) 'A' = 97