2017-08-12 75 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