C#中的string类

string是c#中常用的类型,关于它的使用总结如下。

Length

计算字符串长度,即包含字符的个数。

 string str = "April";           
 int len = str.Length;           //len = 5

==

字符串比较,等于0表示字符串相等。

string str = "April";
bool res = str == "April";     //res = True

CompareTo

比较字符串内容, 字符串相等时返回0。

string str = "April";
int res = str.CompareTo("Harris");     //res = -1

字符串连接

string str = "April";
str = "Hello," + str;          // str = "Hello,April"

[]

取得字符串中的字符

string str = "Hello,April";
char c = str[0];              // c = 'H'

Replace

将指定字符(字符串)替换为另外的字符(字符串)。

 string str = "Hello,April";
 string result1 = str.Replace(',', '!');               //result1 = "Hello!April"        
 string result2 = str.Replace("April", "Harris");      //result2 = "Hello,Harris"

Split

给定字符,将字符串拆分成字符串数组。

 string str = "Hello,April";
 string[] strArray = str.Split(',');                  //strArray = {"Hello","April"}

Substring

检索给定位置的子串

 string str = "Hello,April";
 string result1 = str.Substring(6,3);                  //第6个字符开始,长度为3的子串   result1 = "Apr"
 string result2 = str.Substring(6);                    //第6个字符开始,到最后的子串    result2 = "April"

ToUpper

将字符串转化为大写

 string str = "Hello,April";
 string result = str.ToUpper();                  //result = "HELLO,APRIL"

ToLower

将字符串转化为小写

 string str = "Hello,April";
 string result = str.ToLower();                //result = "hello,april"

Trim

删除首尾的空白

string str = "  Hello,April ";
string result = str.Trim();                  //result = "Hello,April"              

IndexOf

查找字串,返回子串起始的位置,不包含子串时返回-1。

 string str = "Hello,April";
 int index = str.IndexOf("April");            //index = 6

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值