C#替换字符串中子串

 1 using System;    
 2 using System.Collections.Generic;    
 3 using System.Linq;    
 4 using System.Text;    
 5     
 6 class Program    
 7 {    
 8     
 9     /// <summary>    
10     ///     
11     /// </summary>    
12     /// <param name="str">待处理的字符串</param>    
13     /// <param name="toRep">要替换的字符串中的子串</param>    
14     /// <param name="strRep">用来替换toRep字符串的字符串</param>    
15     /// <returns>返回一个结果字符串</returns>    
16     
17     public static string StringReplace(string str, string toRep, string strRep)    
18     {    
19         StringBuilder sb = new StringBuilder();    
20     
21         int np = 0, n_ptmp = 0;    
22     
23         for (; ; )    
24         {    
25             string str_tmp = str.Substring(np);    
26             n_ptmp = str_tmp.IndexOf(toRep);    
27     
28             if (n_ptmp == -1)    
29             {    
30                 sb.Append(str_tmp);    
31                 break;    
32 
33     1.             }    
34 
35             else    
36             {    
37                 sb.Append(str_tmp.Substring(0, n_ptmp)).Append(strRep);    
38                 np += n_ptmp + toRep.Length;    
39             }    
40         }    
41         return sb.ToString();    
42     
43     }    
44     
45     
46     /// <summary>    
47     /// 测试用例:"dwdawdyesdwjdao dyesj yes dwjaodjawiodayes djwaiodyesjijw"    
48     /// </summary>    
49     /// <param name="args"></param>    
50     
51     static void Main(string[] args)    
52     {    
53         string str = Console.ReadLine();    
54         str = StringReplace(str, "yes", "no");    
55         Console.WriteLine(str);    
56         Console.ReadKey();    
57     }    
58 }    

 

posted @ 2017-07-11 11:27  sanpi1992  阅读(1262)  评论(0编辑  收藏  举报