我如何搜索数组中字符串的一部分 [英] how can i search a part of a string in an array

查看:94
本文介绍了我如何搜索数组中字符串的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在字符串数组中搜索字符串的一部分?
在我的字符串数组的一个字段中包含诸如Normaluser1,Normaluser2,admin等之类的值...我必须检查数组的任何字段中是否包含值"Normaluser",如果是,则返回1否则为0(我必须截断数字部分),并且我不知道该字段的地址,其中出现了具有Normaluser值的字符串...
我该如何检查????

How can i search for a part of a string in my string array?
In one of the field of my string array contains values like Normaluser1,Normaluser2,admin etc...i have to check that any one of the field of my array contains value "Normaluser" if yes return 1 else 0 (i have to truncate the number part) and i dnt know the address of that field where string having value Normaluser occures...
how can i check this???

推荐答案

使用LINQ,可以使用FirstOrDefault扩展方法,如下所示:

Using LINQ the FirstOrDefault extension method can be used as follows:

string[] users = new string[]{"Normaluser1","Normaluser2","Admin"};

int searchResult = users.FirstOrDefault (u => u.StartsWith(
    "Normaluser", StringComparison.InvariantCultureIgnoreCase)) == null ? 0 : 1;
Console.WriteLine (searchResult);


编写一个使用foreach遍历数组的方法,并使用string.StartsWith方法 [
Write a method which loops through the array using foreach, and use the string.StartsWith method[^]to check if it matches - you can then confirm the remainder of the string is numeric if you need to.

If you find a match, return 1. If you get to the end of the method, return 0 as it isn''t there. Or better, return true instead of 1 and false instead of 0, and provide the match string as a parameter. That way the method becomes more general and can be reused later.


我认为这是您的要求.

I think this is your requirement.

foreach(string s in yourArray)
{
  bool retutnValue=false;
  string text="Normaluser";
  if(text==s)
  {
    retutnValue = true;
  }
return retutnValue; 
}


这篇关于我如何搜索数组中字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆