字符串操作

1. 判断字符串是否为null或者empty,使用IsNullOrEmpty() 

2.得到字符串中的字符

string str = "abcd";
char letter = str[0]; 

 也可以遍历字符串

foreach(char c in "asdfg")
{
    Console.Write(c + ",');
}

3.字符串内搜索,可以使用Contains, StartWith, EndWith, IndexOf, LastIndexOf, IndexOfAny。

   Contains, StartWith, EndWith返回bool值。IndexOf, LastIndexOf, IndexOfAny返回字符串出现的位置。

4. 字符串处理

   截图字符串 Substring(int startIndex, int length)    startIndex  开始截图的位置,length 要截取的长度

    string str= "qwert".Substring(0,3) // str= qwe

  在指定位置插入或移除字符  Insert(), Remove() 

    string str1 = "asdfg".Insert(1, ", " );  // a, sdfg

    string str2 = "asdfg".Remove(2,2); // afg

  PadLeft 和 PadRight,用特定字符把字符串填充成指定长度.如果没有指定字符,则默认使用空格

   Console.WriteLine("12345".PadLeft(7, '#')); // ##12345

   Console.WriteLine("12345",PadLeft(7));  //  12345

  替换字符串中的字符或者子字符串 Replace

   Console.WriteLine("Hello world".Replace(" ", ","))  // Hello,world

  转换大小写 ToUpper和ToLower

5.分割和连接字符串   Split, Join, Concat的用法

   Split(params char[] separator) 返回的字符串数组包含此实例中的子字符串

   如果 separator 参数为 null 或不包含任何字符,则采用空白字符作为分隔符

   

string[]  words = "my name is xxx".Split();
foreach(var word in words)
{
   Console.WriteLine(word + "|"); //my|name|is|xxx|
}

引用MSDN的代码:

public class SplitTest {
    public static void Main() {

        string words = "This is a list of words, with: a bit of punctuation" +
                       "\tand a tab character.";

        string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });

        foreach (string s in split) {

            if (s.Trim() != "")
                Console.WriteLine(s);
        }
    }
}


Join 连接指定数组的元素或集合的成员,在每个元素或成员之间使用指定的分隔符。     

string[] strs={"my", "name", "is" ,"xxx"};

Console.WriteLine(string.Join(" ", strs)); //在元素之间加入空格

Concat 和Join类似,但是只接受字符串数组,并且没有分隔符. Concat和+的效果相同

String str= string.concat("my", "name", "is", "xxx"); //mynameisxxx

 6. 格式化字符 String.Format

    string str = String.Format("This is a {0}", ”Apple“);

posted @ 2015-06-19 15:31  豆腐爱鱼儿  阅读(124)  评论(0编辑  收藏  举报