我是C#的新手,我正在尝试搜索字符串以查看它是否包含字符串数组的成员。如果该字符串确实包含数组中的某些内容,那么我想记录它找到的数组成员的索引号,然后显示它。
string stringToBeSearched = "I want to find item2 or item6";
string[] array = { "item1", "item2", "item3" };
// Search stringToBeSearched for anything in array, then enter the array
// member's index value into int position
int position = //array index number of item found
Console.WriteLine("{0} was found.", array[position]);
Console.ReadLine();
您可以将每个数组元素与stringToBeSearched
using进行比较IndexOf
。
string stringToBeSearched = "I want to find item2 or item6";
string[] array = {"item1", "item2", "item3"};
int position;
for (int i = 0; i < array.Length; i++) {
string str = array[i];
if (stringToBeSearched.IndexOf(str) >= 0) {
position = i;
Console.WriteLine("{0} was found.", str);
Console.ReadLine();
}
}
// Result:
// item2 was found.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句