2015-08-22 47 views
-1

在字符串中找到單詞的位置最簡單的方法是什麼?如何在c#或python中的字符串中找到單詞的位置?

例如:

the cat sat on the mat

the word "cat" appears in the second position

the word "on" appears in the fourth position

任何幫助,將不勝感激

+1

可能的重複[在C#中用字符串查找文本](http://stackoverflow.com/questions/10709821/find-text-in-string-with-c-sharp) –

回答

0

您可以使用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. 
0

希望這有助於:

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 
0

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; 
相關問題