在字符串中找到單詞的位置最簡單的方法是什麼?如何在c#或python中的字符串中找到單詞的位置?
例如:
the cat sat on the mat
the word "cat" appears in the second position
或
the word "on" appears in the fourth position
任何幫助,將不勝感激
在字符串中找到單詞的位置最簡單的方法是什麼?如何在c#或python中的字符串中找到單詞的位置?
例如:
the cat sat on the mat
the word "cat" appears in the second position
或
the word "on" appears in the fourth position
任何幫助,將不勝感激
您可以使用str.index
在Python中,它將返回第一個出現的位置。
test = 'the cat sat on the mat'
test.index('cat') # returns 4
編輯:重新讀你的問題,你會想要的單詞的位置。要做到這一點,你應該將句子轉換成一個列表:
test = 'the cat sat on the mat'
words = test.split(' ')
words.index('cat') # returns 1, add 1 to get the actual position.
在Python中,你可以使用查找功能:
希望這有助於:
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#的方式:
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;
可能的重複[在C#中用字符串查找文本](http://stackoverflow.com/questions/10709821/find-text-in-string-with-c-sharp) –