user3373589
user3373589

Reputation: 13

Get number of exact substrings

I want to get the number of substrings out of a string.

The inputs are excel formulas like IF(....IF(...))+IF(...)+SUM(..) as a string. I want to count all IF( substrings. It's important that SUMIF(...) and COUNTIF(...) will not be counted.

I thought to check that there is no capital letter before the "IF", but this is giving (certainly) index out of bound. Can someone give me a suggestion?

My code:

for(int i = input.indexOf("IF(",input.length()); 
        i != -1; 
        i= input.indexOf("IF(,i- 1)){

    if(!isCapitalLetter(tmpFormulaString, i-1)){
        ifStatementCounter++;
    }
}

Upvotes: 0

Views: 76

Answers (2)

MrYo
MrYo

Reputation: 1817

I think you can solve your problem by finding String IF(.

Try to do same thing in another way .

For example: 
inputStrin = IF(hello)IF(hello)....IF(helloIF(hello)).... 

inputString.getIndexOf("IF(");

That solves your problem?

Click Here Or You can use regular expression also.

Upvotes: 0

Adrian Shum
Adrian Shum

Reputation: 40036

Although you can do the parsing by yourself as you were doing (that's possibly better for you to learn debugging so you know what your problem is)

However it can be easily done by regular expression:

String s = "FOO()FOOL()SOMEFOO()FOO";

Pattern p = Pattern.compile("\\bFOO\\b");
Matcher m = p.matcher(s);

int count = 0;
while (m.find()) {
    count++;
}

// count= 2

The main trick here is \b in the regex. \b means word boundary. In short, if there is a alphanumeric character at the position of \b, it will not match.

http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

Upvotes: 8

Related Questions