2015-12-01 28 views
0

因此,我發現如何顯示輸入字符串的出現次數,但我不知道如何顯示單詞的外觀以及它所處的單詞的句子。例如,我的輸入字符串是「the」,但是如何將它顯示爲The或THE或在控制檯上枯萎?另外,我將如何顯示該輸入字符串與它所在的句子?例如:「the」,一句話:乾旱枯萎的巴士。如何在文本文件中顯示字符串? (C#控制檯應用程序)

這裏是我的代碼至今:

static void Main(string[] args) 
    { 
     string line; 
     int counter = 0; 

     Console.WriteLine("Enter a word to search for: "); 
     string userText = Console.ReadLine(); 

     string file = "Gettysburg.txt"; 
     StreamReader myFile = new StreamReader(file); 

     int found = 0; 

     while ((line = myFile.ReadLine()) != null) 
     { 
      counter++; 
      if (line.IndexOf(userText, StringComparison.CurrentCultureIgnoreCase) != -1) 
      { 
       Console.WriteLine("Found on line number: {0}", counter); 
       found++; 
      } 
     } 
     Console.WriteLine("A total of {0} occurences found", found); 
    } 
+0

添加另一個Console.WriteLine顯示文字和IF條件中的句子。 – Harsh

回答

0

這聽起來像你想要觸發匹配的單詞,即使它是你的匹配的部分詞。

while ((line = myFile.ReadLine()) != null) 
{ 
    counter++; 
    int index = line.IndexOf(userText, StringComparison.CurrentCultureIgnoreCase); 
    if (index != -1) 
    { 
     //Since we want the word that this entry is, we need to find the space in front of this word 
     string sWordFound = string.Empty; 
     string subLine = line.Substring(0, index); 
     int iWordStart = subLine.LastIndexOf(' '); 
     if (iWordStart == -1) 
     { 
      //If there is no space in front of this word, then this entry begins at the start of the line 
      iWordStart = 0; 
     } 

     //We also need to find the space after this word 
     subLine = line.Substring(index); 
     int iTempIndex = subLine.LastIndexOf(' '); 
     int iWordLength = -1; 
     if (iTempIndex == -1) 
     { //If there is no space after this word, then this entry goes to the end of the line. 
      sWordFound = line.Substring(iWordStart); 
     } 
     else 
     { 
      iWordLength = iTempIndex + index - iWordStart; 
      sWordFound = line.Substring(iWordStart, iWordLength); 
     } 

     Console.WriteLine("Found {1} on line number: {0}", counter, sWordFound); 
     found++; 
    } 
} 

這可能有錯誤,但應該推動你在正確的方向。另外,如果您包含預期的輸出,它會對您的示例有所幫助。

這是我希望出這個代碼是什麼:

input: 
The drought withered the bus. 
Luke's father is well known. 
The THE ThE 

output: 
Found The on line number: 1 
Found withered on line number: 1 
Found the on line number: 1 
Found father on line number: 2 
Found The on line number: 3 
Found THE on line number: 3 
Found ThE on line number: 3 
+0

嗨,所以在使用您的代碼後,字符串子行代碼中出現錯誤,因爲它已被使用兩次。第二個字符串子行是不同的字符串嗎?我將它重命名爲字符串subline2,它能夠工作。非常感謝你的幫助 –

+0

另一個問題,我將如何讓控​​制臺輸出包含「the」的實際單詞。例如,它會像 創建「」在葛底斯堡在父親的行號1 找到「父親」帶來了這個在線人數4 –

+0

高興它能夠爲你工作。是的,它不應該被宣佈兩次。重命名它是一個有效的解決方案。我打算重用這個變量。在上面更正。 sWordFound應該包含找到的詞(用「父親」應該返回「父親」來搜索)。我可能沒有正確的writeline語法。 – Aki

0

如何改變一個行:

Console.WriteLine("Line {0}: {1}", counter,line); 

順便說一句,我不太明白你的問題,這是什麼意思通過「在控制檯上顯示爲或THE或在控制檯上枯萎」,以及「顯示該輸入字符串和它所在的語句」?

相關問題