c#判断字符串是否存在数组
时间: 2023-07-25 07:34:30 浏览: 257
在 C# 中,可以使用 Array.Exists
方法和 String.Equals
方法来判断一个字符串是否存在于一个字符串数组中。示例代码如下:
string[] array = { "apple", "banana", "orange", "pear" };
string str = "banana";
bool exists = Array.Exists(array, element => element.Equals(str));
if (exists)
{
Console.WriteLine($"The string '{str}' exists in the array.");
}
else
{
Console.WriteLine($"The string '{str}' does not exist in the array.");
}
在上面的示例代码中,我们定义了一个字符串数组 array
和一个字符串 str
,然后使用 Array.Exists
方法和 String.Equals
方法来判断 str
是否存在于 array
中。最后根据判断结果输出相应的消息。
相关问题
c#判断字符串是否在数组中
可以使用Array类的Contains方法来判断字符串是否在数组中,示例如下:
string[] array = { "apple", "banana", "cherry" };
string str = "banana";
if (Array.Contains(array, str))
{
Console.WriteLine("字符串在数组中");
}
else
{
Console.WriteLine("字符串不在数组中");
}
注意,需要引入System命名空间。
c#判断字符串数组是否有变化
在 C# 中,如果你想要判断一个字符串数组是否发生了变化,通常的做法是使用集合(Array 或者 List
例如,你可以先将数组转换为HashSet,因为 HashSet 只包含唯一的元素并且对添加、删除操作敏感:
HashSet<string> oldSet = new HashSet<string>(arrayOld);
HashSet<string> newSet = new HashSet<string>(arrayNew);
if (oldSet.SetEquals(newSet))
{
Console.WriteLine("字符串数组未发生变化");
}
else
{
Console.WriteLine("字符串数组已发生变化");
}
如果你想检查数组中的每个元素是否都相同,可以逐个比较:
bool arraysEqual = true;
for (int i = 0; i < arrayOld.Length && i < arrayNew.Length; i++)
{
if (arrayOld[i] != arrayNew[i])
{
arraysEqual = false;
break;
}
}
if (arraysEqual)
{
Console.WriteLine("字符串数组未发生变化");
}
else
{
Console.WriteLine("字符串数组已发生变化");
}
相关推荐













