Reputation: 169
I'm trying to count actual length of integers in a string
I've been using this method to find the length of all the characters
whitespace = input.length() - input.replaceAll(" ", "").length();
len = input.length()-whitespace;
but the problem is when the string contains integers greater then 9
for example "1 2 3 456" which should return 4 instances of integers.
That piece of code results in length of 6.
Another way I've found is
int counter = 0;
for (int i = 0, length = input.length(); i < len; i++) {
if (Character.isDigit(input.charAt(i))) {
counter++;
}
}
but this also counts digits, not integer as a whole.
How could I isolate an integer that is greater then 9 to count them?
Upvotes: 1
Views: 186
Reputation: 862
Check this program.. `
int count = 0;
for(String string : input.split(" ")){
if(isInteger(string)) count++;
}
boolean isInteger( String string )
{
try
{
Integer.parseInt( string );
return true;
}
catch( Exception )
{
return false;
}
}
`
Upvotes: 1
Reputation: 641
String input = "1 2 3 456";
int len=input.split(" ").length;
This will give len as 4.
Upvotes: 3
Reputation: 13844
follow these steps
example
String x="1 2 24";
String x1[]=x.split(" ");
int l1=x1[0].length();
int l2=x1[1].length();
int l3=x1[2].length();
System.out.println(l3+l1+l2);
System.out.println(x1.length());// this will give number of integers in the string
output 4
3
Upvotes: 0
Reputation: 135992
try this
Matcher m = Pattern.compile("\\d+").matcher(s);
int n = 0;
while(m.find()) {
n++;
}
System.out.println(n);
Upvotes: 1
Reputation: 44740
You can try like this -
int count = 0;
for(String s : input.split(" ")){
if(isNumeric(s)) count++;
}
// method to check if string is a number
public boolean isNumeric(String s) {
return s.matches("[-+]?\\d*\\.?\\d+");
}
Upvotes: 1