Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert string to int in java

Tags:

java

string

regex

i have a string that has a int value in it. i just want to extract the int value from the string and print.

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.

like image 206
buttowski Avatar asked Aug 05 '26 17:08

buttowski


1 Answers

try String.replaceAll

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

you will get

365
like image 167
Evgeniy Dorofeev Avatar answered Aug 08 '26 10:08

Evgeniy Dorofeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!