新闻建站cms系统、政府cms系统定制开发

广州网站建设公司-阅速公司

asp.net新闻发布系统、报纸数字报系统方案
/
http://www.ysneo.com/
广州网站建设公司
您当前位置:首页>ASP.NET MVC

ASP.NET MVC

.Net(C#) 实现replace字符串替换只替换一次的方法

发布时间:2021/9/26 17:30:20  作者:Admin  阅读:802  

广告:阿里云采购优惠专区

本文主要介绍.Net(C#)替换字符串时,实现replace替换字符串只替换一次的方法代码。分别通过StringBuilder、正则表达式(Regex)、IndexOf和Substring实现,并且可以通过扩展方法简化代码方便调用。

1、使用StringBuilder替换

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
  class Program
  {
    static void Main(string[] args)
    {
      string str = "hello world! cjavapy!!!";
      StringBuilder sb = new StringBuilder(str);
      str = sb.Replace("!", "b", 0, str.IndexOf("!") + 1).ToString(); ;//指定替换的范围实现替换一次,并且指定范围中要只有一个替换的字符串
      Console.WriteLine(str);//输出:hello worldb cjavapy!!!
      Console.ReadKey();
    }
  }
}

2、使用正则表达式(Regex)替换

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
  class Program
  {
    static void Main(string[] args)
    {
      string str = "hello world! cjavapy!!!";
      Regex regex = new Regex("!");//要替换字符串"!"
      str = regex.Replace(str, "b", 1);//最后一个参数是替换的次数
      Console.WriteLine(str);//输出:hello worldb cjavapy!!!
      Console.ReadKey();
    }
  }
}

3、使用IndexOf和Substring替换

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
  class Program
  {
    static void Main(string[] args)
    {
      string str = "hello world! cjavapy!!!";
      StringBuilder sb = new StringBuilder(str);
      int index = str.IndexOf("!");
      str = str.Substring(0, index) + "b" + str.Substring(index + 1);//指定替换的范围实现替换一次,并且指定范围中要只有一个替换的字符串
      Console.WriteLine(str);//输出:hello worldb cjavapy!!!
      Console.ReadKey();
    }
  }
}

4、通过扩展方法实现ReplaceOne

扩展方法实现代码

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication2
{
public static class StringReplace
{
public static string ReplaceOne(this string str, string oldStr, string newStr)
{
StringBuilder sb = new StringBuilder(str);
int index = str.IndexOf(oldStr);
if (index > -1)
return str.Substring(0, index) + newStr + str.Substring(index + oldStr.Length);
return str;
}
}
}

调用代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
  class Program
  {
    static void Main(string[] args)
    {
      string str = "hello world! cjavapy!!!";
      str = str.ReplaceOne("!","b");//通过扩展方法替换
      Console.WriteLine(str);//输出:hello worldb cjavapy!!!
      Console.ReadKey();
    }
  }
}

广告:阿里云新人采购专场

相关文章
replace
cms新闻系统购买咨询
扫描关注 广州阅速软件科技有限公司
扫描关注 广州阅速科技