分享

【C#】字符串包含的常见方法,Contains、Expect以及IndexOf等

 醉人说梦 2024-03-27 发布于广东

最近都在做C#相关的后台开发工作,会持续一段时间都是更新C#相关的文章,学习和开发C#方向的小伙伴可以浏览和支持下!

1、Contains

Contains 方法是用于判断一个字符串是否包含另一个指定的子字符串。它的语法形式如下:

public bool Contains(string value);

value 参数是要查找的子字符串。如果字符串中包含该子字符串,则返回 true,否则返回 false。

  • 以下是一个示例代码:
string str = "Hello World!";
if (str.Contains("Hello")) // 判断字符串 str 中是否包含 "Hello"
{
    Console.WriteLine("包含子字符串 Hello");
}

2、Expect

Expect 方法是一个字符串扩展方法,它的作用与 Contains 方法一样,也是用于判断一个字符串是否包含另一个子字符串。
但与 Contains 方法不同的是,Expect 方法可以忽略大小写。

  • 它的语法形式如下:
public static bool Expect(this string source, string value, StringComparison comparisonType);

其中,source 参数是要查找的字符串,value 参数是要查找的子字符串,comparisonType 参数则指定了比较方式,包括忽略大小写等。如果字符串中包含该子字符串,则返回 true,否则返回 false。

  • 以下是一个示例代码:
string str = "Hello World!";
if (str.Expect("hello", StringComparison.OrdinalIgnoreCase)) // 判断字符串 str 中是否包含 "hello",并忽略大小写
{
    Console.WriteLine("包含子字符串 hello");
}

总的来说,Contains 方法比较常用,而 Expect 方法则适用于一些要求忽略大小写的场合。

3、IndexOf

在 C# 中,IndexOf 方法用于在字符串中查找指定字符或子字符串的位置。

  • 它的语法形式如下:
public int IndexOf(char value);
public int IndexOf(string value);
public int IndexOf(char value, int startIndex);
public int IndexOf(string value, int startIndex);
public int IndexOf(string value, StringComparison comparisonType);
public int IndexOf(string value, int startIndex, int count, StringComparison comparisonType);

其中:

value 参数是要查找的字符或子字符串;
startIndex 参数是开始查找的位置(默认是从字符串的开头开始查找);
count 参数是要查找的部分的字符数;
comparisonType 参数指定了比较的方式,包括大小写不敏感、大小写敏感等。
IndexOf 方法会返回指定字符或子字符串在原字符串中出现的位置,如果未找到指定字符或子字符串,则返回 -1。需要注意的是,如果 IndexOf 方法没有设置比较方式(如通过 StringComparison 枚举类型设置),则默认是以区分大小写的方式进行字符串比较。

  • 以下是一个示例代码:
string str = "hello world";
int index = str.IndexOf('o'); // 查找字符 'o' 的位置
Console.WriteLine(index); // 输出:4

index = str.IndexOf("world"); // 查找子字符串 "world" 的位置
Console.WriteLine(index); // 输出:6

4、LastIndexOf

LastIndexOf 方法:在字符串中查找指定字符或子字符串最后一次出现的位置。它和 IndexOf 方法类似,不同之处在于它返回最后一次出现的索引位置。

  • 例如:
string str = "Hello World!";
int lastIndex = str.LastIndexOf('o');
Console.WriteLine(lastIndex);  // 输出:7

5、StartsWith

StartsWith方法:用于判断一个字符串是否以指定的字符或子字符串开始。它们返回一个布尔值,表示是否符合条件。

  • 例如:
string str = "Hello World!";
bool startsWith = str.StartsWith("Hello");
Console.WriteLine(startsWith);  // 输出:True

6、EndsWith

StartsWith方法:用于判断一个字符串是否以指定的字符或子字符串结束。它们返回一个布尔值,表示是否符合条件。

  • 例如:
string str = "Hello World!";
bool endsWith = str.EndsWith("World!");
Console.WriteLine(endsWith);  // 输出:True

这些字符串方法提供了不同的方式来检查字符串是否包含指定的字符或子字符串,并可根据具体需求选择合适的方法来使用。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多