0
点赞
收藏
分享

微信扫一扫

第5讲:使用ajax技术实现局部刷新功能(xml数据)

乌龙茶3297 2023-06-29 阅读 63

目录

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");
}

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 条评论