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(); ;//指定替換的范圍實(shí)現(xiàn)替換一次,并且指定范圍中要只有一個替換的字符串
Console.WriteLine(str);//輸出:hello worldb cjavapy!!!
Console.ReadKey();
}
}
}
2、使用正則表達(dá)式(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);//最后一個參數(shù)是替換的次數(shù)
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);//指定替換的范圍實(shí)現(xiàn)替換一次,并且指定范圍中要只有一個替換的字符串
Console.WriteLine(str);//輸出:hello worldb cjavapy!!!
Console.ReadKey();
}
}
}
4、通過擴(kuò)展方法實(shí)現(xiàn)ReplaceOne
擴(kuò)展方法實(shí)現(xiàn)代碼:
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;
}
}
}
調(diào)用代碼:
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");//通過擴(kuò)展方法替換
Console.WriteLine(str);//輸出:hello worldb cjavapy!!!
Console.ReadKey();
}
}
}


