C# string类

一、String类
1、字符串的比较
Compare(str1,str2)
str1.CompareTo(str2)
返回的是:int32
小于0:str1在排序顺序中位于str2之前
等于0:str1与str2在排序顺序中出现的位置相同
大于0:str1在排序顺序中位于str2之后
详细见:
https://docs.microsoft.com/zh-cn/dotnet/api/system.string.compare?view=net-6.0#system-string-compare(system-string-system-string)
2、字符串的查找
Contains(str):查找指定字符是否包含字串str,返回bool类型
IndexOf(str):查找字串str第一次出现的位置,没有则返回-1
LastIndexOf(str):查找最后一次出现的位置,没有则返回-1
例如:
string x=“hello”;
Console.WriteLine(x.IndexOf(‘w’));//-1
Console.WriteLine(x.IndexOf(‘o’));//4
3、字符串的截取
Substring(str):字符串中下标从str开始后面的全部字符串。
Substring(str, Len):字符串中下标从str开始后面的Len个长度的字符串。
例如:
string x=“hello”;
Console.WriteLine(x.Substring(2));//llo
Console.WriteLine(x.Substring(2, 2));//ll
4、字符串的分割
Split(str):将字符串按str进行分割,它的返回值是一个字符串数组。
例如:

string d = "锄禾日当午#汗滴禾下土#谁知盘中餐#粒粒皆辛苦";
string[] dd = d.Split('#');
for (int i = 0; i < dd.Length; i++)
  {
    
    
   Console.WriteLine(dd[i]);
   /* 锄禾日当午
    * 汗滴禾下土
    * 谁知盘中餐
    * 粒粒皆辛苦
    */
  }

5、字符串的合并
string.Concat(str1, str2, …., strn):将n个字符串连接
string xx = “aaa”, yy = “bbb”;
Console.WriteLine(xx + yy);
Console.WriteLine(string.Concat(xx, yy));//这个效率高
6、字符串的删除
Trim():删除字符串中开始和结尾处的空格
例如:
string z = " cc dd ";
Console.WriteLine(z.Trim());//“cc dd”
7、字符串的替换
Replace(oldStr, newStr):用newStr来替换字符串中的oldStr
例如:
string z = " cc dd “;
Console.WriteLine(z.Replace(“cc”, “CC”));//” CC dd "
8、字符串的插入
Insert(index, str):index是需要插入的位置,str是要插入的字符
例如:
string z = " cc dd “;
Console.WriteLine(z.Insert(2, “ww”));//” wwcc dd "
9、字符串大小写转化
ToLower小写,ToUpper大写
string x=“Hello”;
Console.WriteLine(x.ToLower());//hello
Console.WriteLine(x.ToUpper());//HELLO

二、string类习题
1、用户输入一个邮箱账号,提取用户名和域名(@不属于任何一个)

Console.WriteLine("输入邮箱:");
string email = Console.ReadLine();
string[] e = email.Split('@');
for (int i = 0; i < e.Length; i++)
{
    
    
 Console.WriteLine(e[i]);
}

2、用户输入一句话,查询其中e的位置

Console.WriteLine("输入一句话(判断e的位置):");
string words = Console.ReadLine();
int a = words.IndexOf('e');
if (a == -1)
{
    
    
 Console.WriteLine("该句话没有e");
}
else
{
    
    
 Console.WriteLine("e的位置在第:"+(a+1)+"个");
}

3、输入一个字符串,若字符串中出现邪恶,则把它替换为**

Console.WriteLine("输入一句话 :(出现邪恶则换为**)");
string b = Console.ReadLine();
Console.WriteLine(b.Replace("邪恶","**"));

4、将数组中的元素{“林杨”,“余周周”,“言默”,“赵乔一”} 变成 林杨|余周周|言默|赵乔一

string[] name = {
    
     "林阳", "余周周", "炎默", "赵乔一" };
for(int i = 0; i < name.Length; i++)
{
    
    
 if (i < (name.Length - 1))
  {
    
    
   Console.Write(name[i].Insert(name[i].Length, "|"));
  }
 else
  {
    
    
   Console.WriteLine(name[i]);
  }
}

5、把“锄禾日当午#汗滴禾下土#谁知盘中餐#粒粒皆辛苦”变成
锄禾日当午,
汗滴禾下土,
谁知盘中餐,
粒粒皆辛苦。

string s1 = "锄禾日当午#汗滴禾下土#谁知盘中餐#粒粒皆辛苦";
string[] s2 = s1.Split('#');
for (int i = 0; i < s2.Length; i++)
{
    
    
 if (i == s2.Length - 1)
  {
    
    
   Console.WriteLine(s2[i].Insert(s2[i].Length,"。"));
  }
  else
  {
    
    
    Console.WriteLine(s2[i].Insert(s2[i].Length+1, ","));
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_44706943/article/details/126089045