简体   繁体   English

将字符串转换为数字

[英]Converting a string of letters to numbers

Say I have a string phone = "1-800-test" 说我有一个字符串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: 请注意, getNumber()是一个带字母并返回数字的方法:

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? 我该如何用数字代替字母?

(char) 1 is not what you need. (char)1不是你需要的。 You need '1' . 你需要'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 这样做的好方法是为所有字母创建一个Map<Character, Character> ,预先填充它: map.put('t', '8')等,然后

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(..) ) (或者,为了获得更好的性能,请使用StringBuilder's replace(..)indexOf(..)

Doing (char)1 gives you the ASCII character represented by 1 so you get the weird square. 执行(char)1会为您提供由1表示的ASCII字符,这样您就可以得到奇怪的正方形。 You can just use '1' to instead. 您只需使用“1”即可。 If you insist on converting integers to ASCII, just add 48 (since that is where the digits start in the ascii). 如果你坚持将整数转换为ASCII,只需添加48(因为这是数字从ascii开始的位置)。 ie (char)48 is '0', (char)49 is '1' and so on. ie(char)48为'0',(char)49为'1',依此类推。 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... 但不建议......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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