简体   繁体   English

在java中将字符串转换为int

[英]convert string to int in java

i have a string that has a int value in it. 我有一个字符串,其中包含一个int值。 i just want to extract the int value from the string and print. 我只想从字符串中提取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());

is there any better way than this. 有没有比这更好的方法。 please let me know. 请告诉我。

try String.replaceAll 尝试String.replaceAll

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

you will get 你会得到

365

Another way of using regex (other than the way suggested by @EvgeniyDorofeev) which is closer to what you did: 另一种使用正则表达式的方法(除了@EvgeniyDorofeev建议的方式)更接近你所做的:

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

which means, replace everything that is not 0-9 with empty string (or, in another word, remove all non-digit characters) 这意味着,用空字符串替换不是0-9的所有内容(换句话说,删除所有非数字字符)

This is meaning the same, just a matter of taste which one is more comfortable to you: 这意味着相同,只是一个让您感觉更舒服的品味问题:

str.replaceAll("\\D","");   // give you "365"
Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+");
int integer = in.nextInt();

This will get you the integer 这将得到整数

following code gives you integer value 以下代码为您提供整数值

  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

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

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