英文:
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 String
s 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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论