what would be the easiest way to find the position of a word inside a string?
for example:
the cat sat on the mat
the word "cat" appears in the second position
or
the word "on" appears in the fourth position
any help would be appreciated
what would be the easiest way to find the position of a word inside a string?
for example:
the cat sat on the mat
the word "cat" appears in the second position
or
the word "on" appears in the fourth position
any help would be appreciated
You can use str.index
in Python, it will return the position of the first occurrence.
test = 'the cat sat on the mat'
test.index('cat') # returns 4
EDIT: re-reading your question, you'll want the position of the word. To do this, you should convert your sentence into a list:
test = 'the cat sat on the mat'
words = test.split(' ')
words.index('cat') # returns 1, add 1 to get the actual position.
Hope this helps :
s = 'the cat sat on the mat'
worlist = s.split(' ')
pos=1
for word in worlist:
if word == 'cat':
print pos
break
else:
pos = pos + 1
C# way:
string wordToFind = "sat";
string text = "the cat sat on the mat";
int index = text.Split(' ').ToList().FindIndex((string str) => { return str.Equals(wordToFind, StringComparison.Ordinal); }) + 1;