2016-06-21 5 views
-3

テキスト内の正確なインデックスを繰り返す単語を見つける必要があります。たとえば、以下のテキストを参照してください。テキスト内の繰り返し単語のインデックスを見つけるにはどうすればよいですか?

string text = "The first text area sample uses a dialog text to display the errors"; 
text.IndexOf("text"); 

この文字列では、「text」という単語が2回繰り返されます。私は両方の位置のインデックスを取得する必要があります。上記のコードのように "IndexOf"を使用すると、常に10番目の単語 "text"のインデックスを返します。だから、C#を使ってテキスト内の繰り返し単語の正確なインデックスを見つけるにはどうすればよいでしょうか。

答えて

4

ループでそれを行う、C#の

string text = "The first text area sample uses a dialog text to display the errors"; 
int i = 0; 
while ((i = text.IndexOf("text", i)) != -1) 
{ 
    // Print out the index. 
    Console.WriteLine(i); 
    i++; 
} 

はJavaScript

var text = "The first text area sample uses a dialog text to display the errors"; 
var i; 
while ((i = text.IndexOf("text", i)) != -1) 
{ 
    // Print out the index. 
    alert(i); 
    i++; 
} 
+0

'i'は現在のコンテキストに存在しませんか? 'i'はどこで宣言され/初期化されましたか? –

+0

更新された回答。 –

+0

このアップデートでもコンパイルエラーが発生します。 'int'は与えられた文脈では無効な型です..' int i = 0; 'はループの外側で宣言する必要があります –

0

これは、(任意の言語で作業することができます)はJavaScriptソリューションの可能duplicate question次のとおりです。

ここれます他の投稿から与えられた解決策:

function getIndicesOf(searchStr, str, caseSensitive) { 
    var startIndex = 0, searchStrLen = searchStr.length; 
    var index, indices = []; 
    if (!caseSensitive) { 
    str = str.toLowerCase(); 
    searchStr = searchStr.toLowerCase(); 
    } 
    while ((index = str.indexOf(searchStr, startIndex)) > -1) { 
    indices.push(index); 
    startIndex = index + searchStrLen; 
    } 
    return indices; 
} 

getIndicesOf("le", "I learned to play the Ukulele in Lebanon.", false); 
関連する問題