C# 字符串相关操作

一、字符数组转换为字符串→char[]转string

char[] charArray = {'a','b','c','d'};
string str = new string(charArray);
Console.WriteLine(str);
Console.ReadKey();

输出结果:abcd;

二、获得字符串的长度

string number = "1234 5678";
int size = number.Length;
Console.WriteLine(size);
Console.ReadKey();

输出结果:9 

注意:length属性返回的字符串长度是包括字符串中空格

三、获取指定位置的字符

string str = "努力工作是人生最好的投资";
char chr = str[5];
Console.WriteLine(chr);
Console.ReadKey();

输出结果:人

注意:字符串中的索引位置是从0开始的

四、获取字符串索引位置/判断字符串是否包含某个特定的字符

 string str = "we are the world";
 int size = str.IndexOf("e"); //区分大小写
 Console.WriteLine(size);
 Console.ReadKey();

输出结果:1

注意:如果找到特定字符,返回从零开始的索引,未找到返回-1

index方法有多个重载,更多用法请参考相关资料

扩展1:不区分大小写

 string str = "we are the world";
 int size = str.IndexOf("TH",StringComparison.CurrentCultureIgnoreCase);//比较时忽略大小写
 Console.WriteLine(size);  //返回比较的字符在字符串中第一次出现的索引位置 输出结果:7

 扩展2:区分大小写

  string str = "we are the world";
  bool b = str.Contains("TH"); //比较时区分大小写,返回true为包含,false不包含
  Console.WriteLine(b); //输出结果:false

扩展3:查找第2次出现的位置(不区分大小写)

  string str = "we are the world th";
  int firstIndex = str.IndexOf("TH", StringComparison.CurrentCultureIgnoreCase);
  Console.WriteLine(firstIndex); // 第1次查找结果 输出:7
  int secondIndex = str.IndexOf("TH", firstIndex + 1, StringComparison.CurrentCultureIgnoreCase);
  Console.WriteLine(secondIndex); //第2次查找结果 输出:17

五、判断字符串首尾内容

string类提供了两种判断字符串首尾内容的方法,即startswith和endswith方法。其中startswith方法用来判断字符串是否以指定的内容开始,而endswith用来判断字符串是否以指定的字符结束

 string str = "梦想还是要有的,万一实现了呢!";
 bool result = str.StartsWith("梦想");
 Console.WriteLine(result);
 Console.ReadKey();

输出结果:TRUE

注意:如果是返回true,不是返回false

startswith方法有多个重载,如果在判断字符时,不区分大小写,请参考相关资料

六、字符串的大小写转换

大写:ToUpper()

小写:ToLower()

string str = "Learn and Live";
Console.WriteLine(str.ToUpper()) ;
Console.WriteLine(str.ToLower());
Console.ReadKey();

输出:

LEARN AND LIVE
learn and live

七、截取字符串(substring)

string str = "好好学习,天天向上";
Console.WriteLine(str.Substring(2,1));
Console.ReadKey();

输出:学

八、分割字符串(Split)

string str = "老当益壮,宁移白首之心,穷且益坚,不坠青云之志";
char[] separator = { ',' };
string[] splitstring = str.Split(separator,StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < splitstring.Length; i++)
  {
       Console.WriteLine(splitstring[i]);
  }
Console.ReadKey();

输出结果:

老当益壮
宁移白首之心
穷且益坚
不坠青云之志

九、去掉字符串中的空格

 string str = "  Hello World  ";
 string trimmedStr = str.Replace(" ", "");
 Console.WriteLine(trimmedStr); // 输出:HelloWorld
 string str = "Hello\r\nWorld!";
 string result = str.Replace("\r\n", "");
 Console.WriteLine(result); // 输出:HelloWorld!

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值