1.变量定义

View Code
1         //源字符串
2         private static string old = string.Empty;
3         //被替换的字符串
4         private static string replace = string.Empty;
5         //替换成的字符串
6         private static string newStr = string.Empty;

2.替换方法

View Code
 1         /// <summary>
 2         /// 字符串替换
 3         /// </summary>
 4         /// <param name="strSource">源字符串</param>
 5         /// <param name="strFrom">被替换的字符串</param>
 6         /// <param name="strTo">替换成的字符串</param>
 7         /// <returns></returns>
 8         public static string Replace(string strSource, string strFrom, string strTo)
 9         {
10             if (strSource == null)
11             {
12                 return null;
13             }
14             int i = 0;
15             if ((i =strSource.IndexOf(strFrom,i)) >= 0)
16             {
17                 char[] cSrc = strSource.ToCharArray();
18                 char[] cTo = strTo.ToCharArray();
19                 int len = strFrom.Length;
20                 StringBuilder buf = new StringBuilder(cSrc.Length);
21                 //将源字符串与替换成的字符串追加
22                 buf.Append(cSrc,0,i).Append(cTo);
23                 i += len;
24                 int j = i;
25                 //继续向后查找看是否包含被替换的字符串
26                 while ((i = strSource.IndexOf(strFrom, i)) > 0)
27                 {
28                     buf.Append(cSrc, j, i - j).Append(cTo);
29                     i += len;
30                     j = i;
31                 }
32                 buf.Append(cSrc,j,cSrc.Length-j);
33                 return buf.ToString();
34             }
35             return "字符串中没有此药替换的字符串,请重新输入";
36         } 
posted on 2012-05-11 13:59  捣乃忒  阅读(202)  评论(0编辑  收藏  举报