3

我有一个字符串,其中有一个 int 值。我只想从字符串中提取 int 值并打印。

String str="No. of Days : 365";
String daysWithSplChar = str.replaceAll("[a-z][A-Z]","").trim();
char[] ch = daysWithSplChar.toCharArray();
StringBuffer stb = new StringBuffer();
for(char c : ch)
{
  if(c >= '0' && c <= '9')
   {
      stb.append(c);
   }
}

int days = Integer.ParseInt(stb.toString());

有没有比这更好的方法。请告诉我。

4

4 回答 4

9

尝试 String.replaceAll

    String str = "No. of Days : 365";
    str = str.replaceAll(".*?(\\d+).*", "$1");
    System.out.println(str);

你会得到

365
于 2013-05-21T06:05:20.117 回答
2

另一种使用正则表达式的方式(除了@EvgeniyDorofeev 建议的方式)更接近你所做的:

str.replaceAll("[^0-9]","");   // give you "365"

这意味着,用空字符串替换不是 0-9 的所有内容(或者,换句话说,删除所有非数字字符)

这意思是一样的,只是你的口味更舒服:

str.replaceAll("\\D","");   // give you "365"
于 2013-05-21T06:44:53.777 回答
1

以下代码为您提供整数值

  String str = "No. of Days : 365";
        str = str.replaceAll(".*?(\\d+)", "$1");
        System.out.println(str);
        Integer x = Integer.valueOf(str);//365 in integer type
           System.out.println(x+1);//output 366
于 2013-05-21T07:43:42.297 回答
1
Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+");
int integer = in.nextInt();

这将为您提供整数

于 2013-05-21T06:37:52.870 回答