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.
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.
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.
A way to count the occurrence of a character within a string is using the IndexOf() method of the string class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With