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



猜你喜欢

转载自blog.csdn.net/liyazhen2011/article/details/80848433