Substring(), Replace(), Split(), Trim(), Contains(), Endwith(), Remove()字符串操作方法
//字符串操作
string str = ",,abcd'efgh,,dsf''?";
Console.WriteLine("原字符串;\n" + str + "");
Console.Write("\n\n");
//Substring()方法
Console.WriteLine(str.Substring(1, str.Length - 2));//字符串截取,但不会更改原字符串
Console.WriteLine(str);//结果,abcd'efgh,,dsf''
Console.WriteLine();
//Replace()方法
string strReplace = str.Replace(',', '!');//将,替换为!
//string strReplace = str.Replace(",", "!");
Console.WriteLine(strReplace);//结果!!abcd'efgh!!dsf''?
//Split()方法--字符串转数组
string[] strSplit = str.Split(new char[] { ',' });//用字符串中,将字符串隔开,转为数组
Console.WriteLine(strSplit.Length);
foreach (string s in strSplit)//变为数组 [" ","abcd'efgh"," ","dsf''?"]
{
//Console.WriteLine(s);
Console.Write("{0}\t",s);
}
Console.WriteLine();
//Trim()方法
string strTrim = str.Trim(new char[] { ',' });//去除字符串前面与末尾中的,
Console.WriteLine(strTrim); //结果为 abcd'efgh,,dsf''?
//Contains()方法
Console.WriteLine(str.Contains("?"));//判断字符串中是否含有?
Console.WriteLine();
//EndWith()方法
Console.WriteLine(str.EndsWith("?"));//判断字符串末尾是否以?结尾
Console.WriteLine();
//Remove()方法
string strRemove = str.Remove(1, 3);//从索引位置1开始,删除3个字符
Console.WriteLine(strRemove);//结果 ,cd'efgh,,dsf''?
至于Split()方法,详细请看C#中的Split()与Join()详解