Reputation: 3717
So I want to count the number of times a word appears in a string. For example, the number of times the word hello
appears in the following string:
a = "hello my name is helloson or hello this is not a name hello"
If I do:
count(a,"hello")
I get 4, because it includes the helloson
. I wanted to try to get only the when hello appears as a word so I did:
count(a,["hello","hello "," hello ", " hello"])
Except that this also gave me 4. Why is this the case? I looked at the documentation and there was nothing said about ignoring whitespace. Why doesn't this work? I thought it was maybe the ["hello"]
included in the array, but trying:
count(a,["hello "," hello ", " hello"])
Again results in 4. What am I missing here?
Upvotes: 1
Views: 191
Reputation: 593
You can solve this issue using regular expression
The code I write below will store the hello words in matchStr
after match the input string str
with the expression
. The expression is written in regx and it will do the following comparison, the hello word should come between spaces, a beginning of text followed by space or preceded by space at the end of input.
str = "hello my name is helloson , hello or xhello this is not a name hello";
expression = '(\s|^)hello(\s|$)';
matchStr = regexp(str,expression,'match')
length(matchStr)
Upvotes: 3
Reputation: 1248
because "is helloson" contains " hello".
Workaround 1: count(" " + a + " ", " hello ")
Workaround 2: strs = strsplit(a," "); then count how many items in strs are exactly "hello"
Upvotes: 3