轻松学习C#的String类

2019-12-30 11:13:44于丽

                       abcghj
                       123|456|789
四、字符串的替换
       字符串的替换是通过Replace方法实现的,格式为:字符串.Replace(要替换的原字符串,替换后的字符串);
例四,实现对字符串str的替换
 

  1. <span style="font-size:18px;">using System;   using System.Collections.Generic;  
  2. using System.Linq;   using System.Text;  
  3. using System.Threading.Tasks;     
  4. namespace 字符串   {  
  5.  class Program    {  
  6.   static void Main(string[] args)     {  
  7.    string str = "abcadfaslfj";      string replacestr = str.Replace("a","|");//用“|”替换“a”  
  8.    Console.WriteLine(replacestr);      Console.ReadLine();  
  9.   }    }  
  10. }</span>  
?

输出的结果为:|bc|df|slfj
五、字符串的插入与填充
        字符串的插入是通过Insert方法实现的,其格式为:字符串.Insert(插入位置,插入字串)
        字符串的填充是通过PadRight方法和PadLeft方法实现的。
        PadRight方法是在字符串的结尾通过添加指定的重复字符填充字符串,格式为:字符串.PadRight(总长度)(以空格填充)和字符串.PadRight(总长度,要填充的字符)。
        PadLeft方法是在字符串的开头通过添加指定的重复字符填充字符串,格式为:字符串.PadLeft(总长度)(以空格填充)和字符串.PadLeft(总长度,要填充的字符)。
例五、实现对字符串str的插入与填充
 

  1. <span style="font-size:18px;">using System;   using System.Collections.Generic;  
  2. using System.Linq;   using System.Text;