2017-08-12 77 views
-6

我想在一個定義的string中搜索特定單詞,而我正在使用foreach關鍵字,但它不起作用。我的C#程序在這裏出了什麼問題?

我只是一個初學者。請幫我解決這個問題,我不想使用數組。

static void Main(string[] args) 
{ 
    string str = "Hello You are welcome"; 

    foreach (string item in str)  // can we use string here? 
    { 
     if (str.Contains(are);  // I am checking if the word "are" is present in the above string 
      Console.WriteLine("True"); 
      ) 
    } 
+1

錯誤消息(你甚至不包括)清楚地告訴你,你不能做到這一點。您需要['Split'](https://msdn.microsoft.com/en-us/library/system.string.split(v = vs.110).aspx)獲取數組的字符串 – UnholySheep

+2

也是爲什麼你甚至試圖使用'foreach'? 'str.Contains(「are」)'已經檢查一個字是否在字符串中 – UnholySheep

+0

編譯器會告訴你一些** yes/no **問題的答案,比如「我們可以在這裏使用String嗎?」,編譯器說:「不能將類型'字符'轉換爲'字符串'」,所以清楚** no **。 –

回答

0

試試這個

static void Main(string[] args) 
{ 

    string str = "Hello You are welcome"; 
    foreach (var item in str.Split(' ')) // split the string (by space) 
    { 
     if (item == "are") 
     { 
      Console.WriteLine("True"); 
     } 
    } 
} 
+0

這仍然不會編譯 – UnholySheep

4
string str = "Hello You are welcome"; 

if (str.Contains("are")) 
{ 
    Console.WriteLine("True"); 
} 

,或者你的意思是:

string str = "Hello You are welcome"; 

foreach (var word in str.Split()) // split the string (by space) 
{ 
    if (word == "are") 
    { 
     Console.WriteLine("True"); 
    } 
} 
+1

非常感謝你 –

+0

@TestProgrammer標記答案,如果它解決了你的問題。 –

+0

後者可能是你想要的 - 例如,如果'bare'是字符串中的一個單詞,前者將返回true。 – mjwills