-1

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

Matteo
  • 3
  • 1
  • 1
    possible duplicate of [Find text in string with C#](http://stackoverflow.com/questions/10709821/find-text-in-string-with-c-sharp) – M.kazem Akhgary Aug 22 '15 at 16:33

4 Answers4

0

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.
veggie1
  • 717
  • 3
  • 12
0

in python you can use find function:

http://www.tutorialspoint.com/python/string_find.htm

mhbashari
  • 482
  • 3
  • 16
0

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
bane19
  • 384
  • 2
  • 15
0

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;
thewisegod
  • 1,524
  • 1
  • 10
  • 11