• 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 }    
  • 相关阅读:
    几个简单的定律
    poj 2443 Set Operation 位运算
    博弈论 wythff 博弈
    BZOJ 2120 树状数组套平衡树
    HDU 1392 凸包
    ZOJ 1648 线段相交
    HDU 1756 点在多边形内
    SPOJ 1811 LCS 后缀自动机
    BZOJ 1901 树状数组+函数式线段树
    HDU 1086 线段相交(不规范相交模板)
  • 原文地址:https://www.cnblogs.com/YunChao/p/7149705.html
Copyright © 2020-2023  润新知