字符串常用操作

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

        Console.WriteLine( " -------------------test Join  " );
            String str 
=   "" ;
            String[] strArr 
=  {  " aaa " " bbb " " ccc "  };
            str 
=  String.Join( " + " , strArr);
            Console.WriteLine(str); 
// str="aaa+bbb+ccc"

            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));
// -1
        Console.WriteLine( " abc " .CompareTo( " abc " )); // 0
        Console.WriteLine( " abc " .CompareTo( " abcded " )); // -1
        Console.WriteLine( " abcde " .CompareTo( " abc " )); // 1
         Console.WriteLine( string .Compare( " abc " " abc " ));  // 0
        Console.WriteLine( string .Compare( " abdddc " " abc " )); //
        Console.WriteLine( string .Compare( " abd " " abcdd " ));  // -1
            Console.WriteLine( " -------------------test IndexOf " );
            Console.WriteLine(str.IndexOf(
' l ' ));
        
char  [] aaa = { ' e ' , ' H ' , ' o ' };
            Console.WriteLine(str.IndexOfAny(aaa));  
// aaa里的任意字符与str中第一个匹配项的索引,结果为0
        Console.WriteLine(str.LastIndexOfAny(aaa));  // aaa里的任意字符与str中最后一个匹配项的索引,结果为1
            Console.WriteLine( " -------------------test Split " );
            strArr 
=  str.Split( ' , ' );  // 分裂字符串 结果为:strArr[0]=hello  strArr[1]=world
             int  i  =   0 ;
            
while  (i  <  strArr.Length)
            {
                Console.WriteLine(strArr[i]);
                i
++ ;
            }

            Console.WriteLine(
" -------------------test PadLeft " );
            str 
=   " hello " ;
            str 
=  str.PadLeft( 20 ' * ' );  // 20为填充后的字符串总长度
        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);
        str 
=  str.TrimStart(trmchar);  // 只删除开始的trmchar 值,结果为hello&$#
        str  =  str.TrimEnd(trmchar);  // 只删除末尾的trmchar 值,结果为%hello
             string  str1 = string .Copy(str);
            Console.WriteLine(str);

你可能感兴趣的:(字符串)