總結幾個string類下的方法

string str1="abcdbc":
1 :CopyTo;
             char[] tempchar = new char[str1.Length];
            str1.CopyTo(1, tempchar, 1, 3);
//1從字符串中的哪個索引開始拷貝2//目標字符串3//從目標數組中的索引位置開始保存4要拷貝幾個
            ////
            Console.WriteLine(tempchar[0]);//--------空
            Console.WriteLine(tempchar[1]);//---------b
            Console.WriteLine(tempchar[2]);//---------c
            Console.WriteLine(tempchar[3]);//---------d
 
2:IndexOf;
  str1.IndexOf("bc", 1, 2); //------ 1
//1 要檢查的字符 2 開始位置的索引 3  要遍歷的長度這個參數要大於“bc”的長度,不然一定返回-1 沒有這參數表示截止長度是開始位置到結尾
 3:IndexOfAny;
   char[] tempchar2 = new char[] { 'b', 'c' };
     str1.IndexOfAny(tempchar2, 0, 2)----- -1
//1要檢查的字符數組 2 開始檢查幾個始位置的索引 3檢查幾個這個參數要大於參數1數組的長度 沒有這參數表示截止長度是開始位置到結尾
     str1.IndexOfAny(tempchar2); ----------1
//如果不指定表示從0開始到最大長度
這個方法跟IndexOf用法功能相似 就是第一參數不同 第一個可以是 char string 第二個是字符數組
4:Join
         string[] stringtemp = new string[] { "abc", "bc", "dc" };
            Console.WriteLine(string.Join("AA", stringtemp, 1, 2));//1用啥連接,2連接哪個字符串數組 3 從數組哪個元素開始的索引 4 要連接幾個元素
 5:LastIndexOf
             Console.WriteLine(str1.LastIndexOf('c'));//這個非常的賤 他的第二個參數是開始查找的索引位置(不指定默認最後一個元素),讓從後往前找 ,找到的第一個就返回該元素的索引
         
            //找不到就返回-1,第三個參數是 檢查的長度
            Console.WriteLine(str1.LastIndexOf('c', 0));//從0索引位置開始 從右往左找
            Console.WriteLine(str1.LastIndexOf('c', 1));//從1索引位置開始 從右往左找
            Console.WriteLine(str1.LastIndexOf('c', 2));//從2索引位置開始 從右往左找
6:PadLeft, PadRight,Remove,Replace
            Console.WriteLine("" + str1.PadLeft(10, '*'));//用*左填充夠10個字符串
            Console.WriteLine("" + str1.PadRight(10, '*'));//用*右填充夠10個字符串
            Console.WriteLine(str1.Remove(0, 2));//1 從哪個位置上開始移除 2 移除幾個
             Console.WriteLine(str1.Replace('a', 'V'));// 用 V 替換 a
7:.Split
以分割字符數組中的字符進行分割,分割數組有2種字符就把字符串分割出3個數組 如果沒有參數就以空格爲分隔符
      //string  temp="a bc  d"
       //char[] tempchar11 = new char[] { 'c' };
            //string[] words = temp.Split();//以空格分割
            //Console.WriteLine(words[0]);----a
           //Console.WriteLine(words[0]);----bc 
           //Console.WriteLine(words[0]);----d
            //Console.WriteLine(temp.Split(tempchar11)[1] );----a b
            //Console.WriteLine(temp.Split(tempchar11)[0] );---  d
8:Trim , TrimEnd,TrimStart
  分別消除(開始結尾處,結尾處,開始處)指定數組內的字符
不指定參數 默認爲空格
              string aaa = "";
            string sentence = ",The ,dog ,had ,a bone, a ball, and other toys.  ";
            char[] charsToTrim = { ',', '.', ' ' };
            string[] words = sentence.Split();
            foreach (string word in words)
            {
                aaa += word.Trim(charsToTrim) + "\n";//移除當前字符串前後的數組內的字符

                //aaa += word.TrimEnd(charsToTrim) + "\n";//移除當前字符串後面的數組內的字符
                //aaa += word.TrimStart(charsToTrim) + "\n";//移除當前字符串後面的數組內的字符
            }
      Console.WriteLine(aaa);
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章