Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string of letters to numbers

Tags:

java

Say I have a string phone = "1-800-test"

I need to convert the letters to numbers.

Doing something like this doesn't work (note I'm looping it of course):

phone = phone.replace(phone.charAt(9), (char) getNumber(phone.charAt(9)));

Note that getNumber() is a method that takes a letter and returns a number:

int getNumber(char uppercaseLetter)

Anyway, I get some weird output with the letter replaced by a weird square.

How should I replace the letters with numbers?

like image 851
Amir Avatar asked Jan 29 '26 06:01

Amir


2 Answers

(char) 1 is not what you need. You need '1'.

The good way to do that is to create a Map<Character, Character>, pre-populate it: map.put('t', '8'), etc for all letters, and then

for (...) {
   Character letter = phone.charAt(i);
   Character digit = map.get(Character.toLowerCase(letter));
   if (digit != null) {
      phone = phone.replace(letter, digit);
   } 
}

A trivial solution would be to just have one line for each character:

phone = phone.replace('a', '2');
phone = phone.replace('b', '2');
//etc..

(or, for better performance, utilize StringBuilder's replace(..) and indexOf(..))

like image 93
Bozho Avatar answered Jan 30 '26 19:01

Bozho


Doing (char)1 gives you the ASCII character represented by 1 so you get the weird square. You can just use '1' to instead. If you insist on converting integers to ASCII, just add 48 (since that is where the digits start in the ascii). i.e. (char)48 is '0', (char)49 is '1' and so on. That doesn't seem necessary for me though.

The exact answer to your question, is use:

phone = phone.replace(phone.charAt(9), (char)(48+getNumber(phone.charAt(9))));

But it is NOT recommended...

like image 22
idanzalz Avatar answered Jan 30 '26 20:01

idanzalz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!