Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count the number of occurrences of a charSequence in a String in Groovy

Tags:

string

groovy

For Example if this is my equation string,

IF(AND(x>0,x<100),5,IF(AND(x>101,x<200),6,10))

I want to count the no:of occurrences of "IF(" string in the equation.

like image 920
Maria Avatar asked Nov 20 '15 10:11

Maria


People also ask

How do you count the number of occurrences of a string in a string?

Approach: First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.

How do you count specific occurrences of character in a string?

The string count() method returns the number of occurrences of a substring in the given string. In simple words, count() method searches the substring in the given string and returns how many times the substring is present in it.

How do you count occurrences in C#?

A way to count the occurrence of a character within a string is using the IndexOf() method of the string class.


1 Answers

E.g. this way:

def s = "IF(AND(x>0,x<100),5,IF(AND(x>101,x<200),6,10))"
assert 2 == s.count("IF(")

In more advanced example you would probably need to use regex.

like image 58
Opal Avatar answered Oct 10 '22 21:10

Opal