首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何比较字符串数组的值?

如何比较字符串数组的值?
EN

Stack Overflow用户
提问于 2017-07-06 14:22:17
回答 3查看 1.3K关注 0票数 1

我已经声明了一个字符串数组,我想将其与用户指定的名称进行比较,

代码语言:javascript
复制
string[] MasterList = new string[] {
  "Askay", "Puram", "Raman", "Srinivasa",
  "Gopal", "Rajesh", "Anju", "Nagara",
};

string YourName;
Console.WriteLine("Enter your name: ");
YourName = Console.ReadLine();

for(i=0; i<5; i++)
{
    a = String.Compare(MasterList[i], YourName);
    Console.WriteLine("Your name is not among the list")
}

结果的输出不是我所期望的,有什么想法我可以怎么做吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-07-06 14:27:25

代码语言:javascript
复制
bool found = false;
foreach (string s in MasterList)
{
    if(s == YourName)
    found = true;
}
if(found)
    Console.WriteLine("Your name is among the list");
else
    Console.WriteLine("Your name is not among the list");
票数 -1
EN

Stack Overflow用户

发布于 2017-07-06 14:25:04

为什么不使用Contains方法呢?

首先在使用指令中添加以下行:

代码语言:javascript
复制
using System.Linq;

然后,删除for循环并使用以下行:

代码语言:javascript
复制
if (!MasterList.Contains(YourName, StringComparer.OrdinalIgnoreCase))
{
    Console.WriteLine("Your name is not among the list")
}
票数 2
EN

Stack Overflow用户

发布于 2017-07-06 14:26:03

为什么不Contains

代码语言:javascript
复制
  string[] MasterList = new string[] {
    "Askay", "Puram", "Raman", "Srinivasa",
    "Gopal", "Rajesh", "Anju", "Nagara",
  };

  Console.WriteLine("Enter your name: ");
  string YourName = Console.ReadLine();

  // StringComparer.OrdinalIgnoreCase if you want to ignore case
  // MasterList.Contains(YourName) if you want case sensitive 
  if (!MasterList.Contains(YourName, StringComparer.OrdinalIgnoreCase))
    Console.WriteLine("Your name is not among the list")
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44951633

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档