判断字符串是否以某个字符串开始、结束、有没有字符串:
- StartsWith 判断字符串是否以某个字符串开始
- EndsWith 判断字符串是否以某个字符串结束
- Contains 判断有没有字符串
StartsWish、EndWith、Contains、减少代码冗余,三者结合一起使用,注释其中两个,以Contains为例:
string str = "呵呵,小崔很纯洁";
//bool result=str.StartsWith("哈"); //判断字符串是否以某个字符串开始
//bool result=str.EndsWith ("纯洁"); //判断字符串是否以某个字符串结束
bool result = str.Contains("呵呵"); //判断有没有字符串
if (result)
{
Console.WriteLine("有这个字符串"); //输出
}
else
{
Console.WriteLine("没有这个字符串"); //输出
}
Console.ReadKey();
输出结果:有这个字符串
- IndexOf 如果字符在这个字符串中,那么就会把这个字符串的索引显示出来,如果没有就返回-1.
string str = "小赵很纯洁";
int index = str.IndexOf("纯"); //如果这个字符在这个字符串中,那么就会把这个字符串的索引显示出来,那么,如果找不到这个字符串返回的结果是-1.
Console.WriteLine(index);
Console.ReadKey();
输出结果为:3