2012-01-10 55 views
-3

我希望用户写出他希望的任何字符串(一个单词或整个句子),然后我想要查找每个“in”并将其替换为“ ter“,但在更换之前,应打印每个”in“的位置。c#关于计数单词“in”的建议并将其替换为“ter”

Console.Write("Write some string: "); 
    string s1 = Console.ReadLine(); 

    s1 = s1.Replace("in", "ter"); 
    Console.WriteLine("After replacement we got new string {0}!", s1); 
    Console.ReadKey(true); 
+5

'IndexOf'是你的朋友。有一个重载需要一个开始索引。使用该重载查找所有事件。 – CodesInChaos 2012-01-10 20:20:28

+1

这是一项家庭作业.. – MethodMan 2012-01-10 20:21:19

+0

IndexOf的文档:http://msdn.microsoft.com/en-us/library/k8b1470s.aspx – 2012-01-10 20:21:48

回答

2

您正在寻找IndexOf

bool done = false; 
int startIndex = 0; 
while (!done) 
{ 
    var index = s1.IndexOf("in", startIndex); 
    if (index < 0) 
    { 
     done = true; 
    } 
    else 
    { 
     Console.WriteLine("Found at position {0}", index); 
     startIndex = index + 2; 
    } 
    if (startIndex >= s1.Length) 
    { 
     done = true; 
    } 
} 
+0

谢谢克里斯Wue - 我从来没有使用var,但即使如此它的工作,并感谢你大时间*拥抱* – 2012-01-10 20:38:05

+0

@KristyMaitz请参阅MSDN:http:// msdn。 microsoft.com/en-us/library/bb383973.aspx – ChrisWue 2012-01-10 20:44:04

+5

呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜声 – ean5533 2012-01-10 20:44:32

1

要找到短语的单个出现,您可以使用IndexOf。例如:

string s = "The word 'in' is in my test sentence two times."; 
int index = s.IndexOf("in"); 

这会给你的世界第一位置“”(否则会返回-1如果没有找到的话)。

但是,由于可能会出现多个您要查找的单词,因此您必须稍微复杂一点。 This StackOverflow question对找到多个词的方式有很好的讨论。

+0

谢谢你抽出时间给我建议 - *拥抱* – 2012-01-10 20:39:08

2

为了ChrisWue的answer更短,这里是一个更新版本:

public void DisplayAllIndexes(string text, string search) 
{ 
    //Argument Validation 
    if (text == null) throw new ArgumentNullException("text"); 
    if (search == null) throw new ArgumentNullException("search"); 

    int index = 0; 

    while ((index = text.IndexOf(search, index)) != -1) 
    { 
     Console.WriteLine("Found at position {0}", index); 

     index += search.Length; 
    } 
}