C# 字符串

从今天开始记录c#之路

C#学习  字符串

      C#的字符串是引用类型,不可变性和密封性是字符串类型的两个类型,字符串一旦创建就不能修改了,所有看上修改了的字符串只是创建了一个新的字符串并返回一个对新字符串的引用。

      字符串类型不能被继承

  • 格式化字符串
string str = "my name is {0},I like {1},My age is{2}";
Console.WriteLine(string.Format(str,"minlecun","tudou","26"));
  • 连接字符串
string str1 = "hello";
string str2 = " ";
string str3 = "world";
Console.WriteLine(string.Concat(str1, str2, str3));
  • 遍历字符串

     可以像数组一样遍历字符串
     string theString = "hello,world";
     char theFristChar = theStringp[0];
     字符是只读的,不能对单个字符进行修改
     string theString = "hello,world";
     theString[0] = 's';//wrong

  • 与数组类似,可以用Length获得字符串长度
  • 可以用foreach对字符串进行遍历
     string theString = "hi,world";
foreach(char s in theString)
{
Console.Write(s);
}



  • 可以通过ToCharArray()形式来获得表示字符串的字符数组
   string theString = "hello World";
char[] theChars = theString.ToCharArray();



  • Trim去2头的空格,TrimStart去开头的指定字符串,TrimEnd去结尾的指定字符串
   string s = "aaasssddd";
string s1 = "asasasddd";
Console.WriteLine(s.TrimStart(new char[] {'a','s'})); //ddd.
Console.WriteLine(s1.TrimStart(new char[] {'a','s'})); //sasasddd.
  • PadLeft或PadRight 添加开头和结尾的指定的字符
   string s = "12345";
Console.WriteLine(s.PadLeft(10,'v')); //vvvvv12345
string s = "12345";
Console.WriteLine(s.PadLeft(5,'v')); //12345
string s = "12345";
Console.WriteLine(s.PadLeft(3,'v')); //12345
  • split 将字符串按指定的字符分割成字符串片段,得到的是字符串数组
            string str = "one two_three=four";
string[] arr = str.Split(new char[] {' ','_','='});
foreach (string s in arr) {
Console.WriteLine(s);
}



  • substring 可以获取指定位置到结束的字符串片段 第一个参数是起始位置 第2个是截取字符串的长度
            string str="0123456789";
string newStr = str.Substring(3);
Console.WriteLine(newStr);
string newStr2 = str.Substring(3,1);
Console.WriteLine(newStr2);

 

  • repalce 替换字符串指定的字符串
            string str = "asdasdzxc";
Console.WriteLine(str.Replace('a', '1'));

 

  • remove 删除字符串中指定位置的字符串片段 第一参数是位置 第2个参数是长度
            string str = "0123456789";
Console.WriteLine(str.Remove(5));
Console.WriteLine(str.Remove(5,1));

 

  • indexOf 查找指定的字符串在字符串中得位置,第一个参数是要查找的字符串 第2个参数起始位置
            string str = "ok is ok";
Console.WriteLine(str.IndexOf("ok"));
Console.WriteLine(str.IndexOf("ok",1));




posted on 2011-12-01 23:45  minlecun  阅读(635)  评论(0编辑  收藏  举报