C#替换字符串中第一个出现的指定字符串

Regex r = new Regex(childstr);
str = r.Replace(str, "", 1);

应用1:已知一个字符串,比如asderwsde,寻找其中的一个子字符串比如sde 的个数,如果没有返回0,有的话返回子字符串的个数。

public static int getnum(string str,string childstr)
{
      int num = 0;
      if (str == "" || childstr == "")
      {
           return num;
      }
      while (str.IndexOf(childstr) > 0)
      {
           Regex r = new Regex(childstr);
           str = r.Replace(str, "", 1);
           num++;
      }
      return num;
}

来自:https://blog.csdn.net/qq_33380252/article/details/107941469

应用2:替换字符串中第一个符合的字符串

string str1 = "abcdefgabchijkabc";
Regex regex2 = new Regex("abc");
string replaceStr = regex2.Replace(str1, "", 1);
Console.WriteLine(replaceStr);//输出defgabchijkabc

 

posted @ 2022-08-29 20:01  东经115  阅读(1204)  评论(0编辑  收藏  举报