c#判断字符串是否存在数组
时间: 2023-07-25 12:34:30 浏览: 82
在 C# 中,可以使用 `Array.Exists` 方法和 `String.Equals` 方法来判断一个字符串是否存在于一个字符串数组中。示例代码如下:
```csharp
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方法来判断字符串是否在数组中,示例如下:
```csharp
string[] array = { "apple", "banana", "cherry" };
string str = "banana";
if (Array.Contains(array, str))
{
Console.WriteLine("字符串在数组中");
}
else
{
Console.WriteLine("字符串不在数组中");
}
```
注意,需要引入System命名空间。
C# 如何判断字符串变量的值在字符串常量数组中是否存在?
你可以使用 C# 中的 `Contains` 方法来判断一个字符串变量的值是否在字符串常量数组中存在。具体实现如下:
```csharp
string[] array = { "apple", "banana", "orange", "grape" };
string variable = "banana";
if (array.Contains(variable))
{
Console.WriteLine("变量的值在数组中存在");
}
else
{
Console.WriteLine("变量的值在数组中不存在");
}
```
在上面的代码中,我们首先定义了一个字符串常量数组 `array`,然后定义了一个字符串变量 `variable`,它的值为 "banana"。接着,在 if 语句中使用 `Contains` 方法判断 `array` 数组中是否包含 `variable` 变量的值,如果存在则输出 "变量的值在数组中存在",否则输出 "变量的值在数组中不存在"。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)