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.
try 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:
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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.