今天静下心来认真的学习了关于字符串的一些操作,因为要用,所以,尽管都是最基本的操作,还是记一下吧。
包括:
1.比较字符串:Compare、CompareTo、Equals、==、!=
2.定位字符和子串:StartWith/EndsWith、IndexOf/LastIndexOf、IndexOfAny/LastIndexOfAny
3.格式化字符串:Format
4.连接字符串:Concat、Join、+
5.分裂字符串:Split
6.插入和填充字符串:Insert、PadLeft/PagRight
7.删除和剪切字符串:Remove、Trim/TrimStart/TrimEnd
8.复制字符串:Copy、CopyTo
9.替换字符串:Replace
10.更改大小写:ToUpper/ToLower
代码如下:
class
Program
{
static void Main(string[] args)
{
Console.WriteLine("-------------------test Join ");
String str = "";
String[] strArr = { "aaa", "bbb", "ccc" };
str = String.Join("+", strArr);
Console.WriteLine(str);
Console.WriteLine("-------------------test Format");
String strA = "Hello";
String strB = "World";
str = String.Format("{0},{1}!",strA,strB);
Console.WriteLine(str);
Console.WriteLine("-------------------test CompareTo");
Console.WriteLine(strA.CompareTo(strB));
Console.WriteLine("-------------------test IndexOf");
Console.WriteLine(str.IndexOf('l'));
Console.WriteLine("-------------------test Split");
strArr = str.Split('+');
int i=0;
while(i<strArr.Length){
Console.WriteLine(strArr[i]);
i++;
}
Console.WriteLine("-------------------test PadLeft");
str = "hello";
str = str.PadLeft(20,'*');
Console.WriteLine(str);
Console.WriteLine("-------------------test Remove");
str = "abcdefg";
str = str.Remove(1,3);
Console.WriteLine(str);
Console.WriteLine("-------------------test Trim");
str = "%hello&$#";
char[] trmchar ={ '%','&','$','#'};
str = str.Trim(trmchar);
Console.WriteLine(str);
}
}
{
static void Main(string[] args)
{
Console.WriteLine("-------------------test Join ");
String str = "";
String[] strArr = { "aaa", "bbb", "ccc" };
str = String.Join("+", strArr);
Console.WriteLine(str);
Console.WriteLine("-------------------test Format");
String strA = "Hello";
String strB = "World";
str = String.Format("{0},{1}!",strA,strB);
Console.WriteLine(str);
Console.WriteLine("-------------------test CompareTo");
Console.WriteLine(strA.CompareTo(strB));
Console.WriteLine("-------------------test IndexOf");
Console.WriteLine(str.IndexOf('l'));
Console.WriteLine("-------------------test Split");
strArr = str.Split('+');
int i=0;
while(i<strArr.Length){
Console.WriteLine(strArr[i]);
i++;
}
Console.WriteLine("-------------------test PadLeft");
str = "hello";
str = str.PadLeft(20,'*');
Console.WriteLine(str);
Console.WriteLine("-------------------test Remove");
str = "abcdefg";
str = str.Remove(1,3);
Console.WriteLine(str);
Console.WriteLine("-------------------test Trim");
str = "%hello&$#";
char[] trmchar ={ '%','&','$','#'};
str = str.Trim(trmchar);
Console.WriteLine(str);
}
}
接下来看StringBuilder.