我在将字符串转换为整数时遇到了问题,因为字符串并不全是数字。

huangapple go评论76阅读模式
英文:

I'm getting trouble converting String to int while the String is not all numbers

问题

我想将从 TextInput 得到的一些 String 转换为 int,只是我不知道如何去除那些非数字的部分。这里有一个例子:

String text = "My number is 0111-473-8922";

有没有办法去除文本和破折号(基本上是任何非数字的字符),以便我可以将其转换为 int

提前感谢您的帮助。

英文:

I would like to convert some of the Strings I get from TextInput to int, only I don't know how to remove the parts that are not numbers. Here's an example:

String text = "My number is 0111-473-8922";

Is there a way to remove the text and dashes (basically whatever isn't a number) so I could convert it to int?

Thanks for your help in advance.

答案1

得分: 0

你可以使用简单的正则表达式来解析结果:

String text = "My number is 0111-473-8922";
try {
    int number = Integer.parseInt(text.replaceAll("[^\\d]", ""));
    System.out.println("number: " + number);
} catch (Exception e) {
    System.out.println("error: " + e);
}
英文:

You can use a simple regex and parse the result:

String text = "My number is 0111-473-8922";
try{
     int number = Integer.parseInt(text.replaceAll("[^\\d]", ""));
     System.out.println("number: " + number);
}catch(Exception e){
     System.out.println("error: " + e);
}

huangapple
  • 本文由 发表于 2020年9月16日 03:28:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63908638.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定