【问题标题】:I'm getting trouble converting String to int while the String is not all numbers [closed]我在将 String 转换为 int 时遇到问题,而 String 并非全是数字 [关闭]
【发布时间】:2021-01-02 14:41:02
【问题描述】:

我想将我从 TextInput 获得的一些Strings 转换为int,只是我不知道如何删除不是数字的部分。这是一个例子:

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

有没有办法删除文本和破折号(基本上不是数字),以便我可以将其转换为 int

提前感谢您的帮助。

【问题讨论】:

  • 查找正则表达式 (regex) 以执行此操作
  • 以后请先搜索你的问题,在你的问题中展示你努力的结果

标签: java string types integer


【解决方案1】:

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

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 2018-02-28
    相关资源
    最近更新 更多