Flow
Flow

Reputation: 169

finding number of integers in a string(not digits)

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

Answers (5)

Sikander
Sikander

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

dpk
dpk

Reputation: 641

String input = "1 2 3 456";

int len=input.split(" ").length;

This will give len as 4.

Upvotes: 3

SpringLearner
SpringLearner

Reputation: 13844

follow these steps

  1. split the string wherever space is present .split(" ")
  2. splitted string is of array type
  3. now count the length of each splitted array
  4. the last step is to add all the lengths(if you want to calculate the number of integers)
  5. use length method of the splitted array to know the number of integer instances

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

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

try this

    Matcher m = Pattern.compile("\\d+").matcher(s);
    int n = 0;
    while(m.find()) {
        n++;
    }
    System.out.println(n);

Upvotes: 1

Adil Shaikh
Adil Shaikh

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

Related Questions