Replace 的作用就是,通過指定內容的替換,返回一個新字串。
返回值中,已將當前字串中的指定 Unicode 字元或 String 的 所有匹配項,替換為指定的新的 Unicode 字元或 String。
String.Replace() 總共有四個過載,分別是:(詳見官網:String.Replace 方法)
Replace(Char, Char)、
Replace(String, String)、
Replace(String, String, StringComparison)、
Replace(String, String, Boolean, CultureInfo)。
下面來逐個簡單介紹下。
// 作用:
// 將範例中出現的所有指定 Unicode 字元都替換為另一個指定的 Unicode 字元。
// 語法:
public string Replace (char oldChar, char newChar);
程式碼範例:
String str = "1 2 3 4 5 6 7 8 9";
Console.WriteLine($"Original string: {str}");
Console.WriteLine($"CSV string: {str.Replace(' ', ',')}");
// 輸出結果:
// Original string: "1 2 3 4 5 6 7 8 9"
// CSV string: "1,2,3,4,5,6,7,8,9"
現在補充一下關於 Char 型別:
char 型別關鍵字是 .NET System.Char 結構型別的別名,它表示 Unicode UTF-16 字元。
型別 | 範圍 | 大小 | .NET 型別 | 預設值 |
char | U+0000 到 U+FFFF | 16 位 | System.Char | \0 即 U+0000 |
// 給 Char 型別的變數賦值可以通過多重方式,如下:
var chars = new[]
{
'j', //字元文字
'\u006A', //Unicode 跳脫序列,它是 \u 後跟字元程式碼的十六進位製表示形式(四個符號)
'\x006A', //十六進位制跳脫序列,它是 \x 後跟字元程式碼的十六進位製表示形式
(char)106, //將字元程式碼的值轉換為相應的 char 值
};
Console.WriteLine(string.Join(" ", chars));
// 輸出的值相同: j j j j
char 型別可隱式轉換為以下整型型別:ushort、int、uint、long 和 ulong。
也可以隱式轉換為內建浮點數值型別:float、double 和 decimal。
可以顯式轉換為 sbyte、byte 和 short 整型型別。
// 作用:
// 範例中出現的所有指定字串都替換為另一個指定的字串
// 語法:
public string Replace (char oldString, char newString);
範例:
// 目的:將錯誤的單詞更正
string errString = "This docment uses 3 other docments to docment the docmentation";
Console.WriteLine($"The original string is:{Environment.NewLine}'{errString}'{Environment.NewLine}");
// 正確的拼寫應該為 "document"
string correctString = errString.Replace("docment", "document");
Console.WriteLine($"After correcting the string, the result is:{Environment.NewLine}'{correctString}'");
// 輸出結果:
// The original string is:
// 'This docment uses 3 other docments to docment the docmentation'
//
// After correcting the string, the result is:
// 'This document uses 3 other documents to document the documentation'
//
另一個範例:
// 可進行連續多次替換操作
String s = "aaa";
Console.WriteLine($"The initial string: '{s}'");
s = s.Replace("a", "b").Replace("b", "c").Replace("c", "d");
Console.WriteLine($"The final string: '{s}'");
// 如果 newString 為 null,則將 oldString 的匹配項全部刪掉
s = s.Replace("dd", null);
Console.WriteLine($"The new string: '{s}'");
// 輸出結果:
//The initial string: 'aaa'
//The final string: 'ddd'
//The new string: 'd'
相較於上一個過載,新增了一個入參列舉型別 StringComparison(詳見官網:StringComparison 列舉)。作用是:指定供 Compare(String, String) 和 Equals(Object) 方法的特定過載,使用的區域性、大小寫和排序規則。
相關原始碼如下,可以看出,不同的 StringComparison 引數值對應的操作不同,最主要的區別就是是否新增引數 CultureInfo。
public string Replace(string oldValue, string? newValue, StringComparison comparisonType)
{
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return ReplaceCore(oldValue, newValue, CultureInfo.CurrentCulture.CompareInfo,
GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return ReplaceCore(oldValue, newValue, CompareInfo.Invariant,
GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.Ordinal:
return Replace(oldValue, newValue);
case StringComparison.OrdinalIgnoreCase:
return ReplaceCore(oldValue, newValue, CompareInfo.Invariant, CompareOptions.OrdinalIgnoreCase);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType");
}
}
關於不同區域的不同 CultureInfo 範例,程式執行結果的區別,見下面的範例:
// 以下範例為三種語言("zh-CN", "th-TH", "tr-TR")不同列舉值的測試程式碼和輸出結果:
String[] cultureNames = { "zh-CN", "th-TH", "tr-TR" }; // 中國 泰國 土耳其
String[] strings1 = { "a", "i", "case", };
String[] strings2 = { "a-", "\u0130", "Case" };
StringComparison[] comparisons = (StringComparison[])Enum.GetValues(typeof(StringComparison));
foreach (var cultureName in cultureNames)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName);
Console.WriteLine("Current Culture: {0}", CultureInfo.CurrentCulture.Name);
for (int ctr = 0; ctr <= strings1.GetUpperBound(0); ctr++)
{
foreach (var comparison in comparisons)
Console.WriteLine(" {0} = {1} ({2}): {3}", strings1[ctr], strings2[ctr], comparison,
String.Equals(strings1[ctr], strings2[ctr], comparison));
Console.WriteLine();
}
Console.WriteLine();
}
// 輸出結果:
// Current Culture: zh-CN
// a = a- (CurrentCulture): False //-----注意------
// a = a- (CurrentCultureIgnoreCase): False //-----注意------
// a = a- (InvariantCulture): False
// a = a- (InvariantCultureIgnoreCase): False
// a = a- (Ordinal): False
// a = a- (OrdinalIgnoreCase): False
//
// i = İ (CurrentCulture): False
// i = İ (CurrentCultureIgnoreCase): False //-----注意------
// i = İ (InvariantCulture): False
// i = İ (InvariantCultureIgnoreCase): False
// i = İ (Ordinal): False
// i = İ (OrdinalIgnoreCase): False
//
// case = Case (CurrentCulture): False
// case = Case (CurrentCultureIgnoreCase): True
// case = Case (InvariantCulture): False
// case = Case (InvariantCultureIgnoreCase): True
// case = Case (Ordinal): False
// case = Case (OrdinalIgnoreCase): True
//
//
// Current Culture: th-TH
// a = a- (CurrentCulture): True //-----注意------
// a = a- (CurrentCultureIgnoreCase): True //-----注意------
// a = a- (InvariantCulture): False
// a = a- (InvariantCultureIgnoreCase): False
// a = a- (Ordinal): False
// a = a- (OrdinalIgnoreCase): False
//
// i = İ (CurrentCulture): False
// i = İ (CurrentCultureIgnoreCase): False
// i = İ (InvariantCulture): False
// i = İ (InvariantCultureIgnoreCase): False
// i = İ (Ordinal): False
// i = İ (OrdinalIgnoreCase): False
//
// case = Case (CurrentCulture): False
// case = Case (CurrentCultureIgnoreCase): True
// case = Case (InvariantCulture): False
// case = Case (InvariantCultureIgnoreCase): True
// case = Case (Ordinal): False
// case = Case (OrdinalIgnoreCase): True
//
//
// Current Culture: tr-TR
// a = a- (CurrentCulture): False
// a = a- (CurrentCultureIgnoreCase): False
// a = a- (InvariantCulture): False
// a = a- (InvariantCultureIgnoreCase): False
// a = a- (Ordinal): False
// a = a- (OrdinalIgnoreCase): False
//
// i = İ (CurrentCulture): False
// i = İ (CurrentCultureIgnoreCase): True //-----注意------
// i = İ (InvariantCulture): False
// i = İ (InvariantCultureIgnoreCase): False
// i = İ (Ordinal): False
// i = İ (OrdinalIgnoreCase): False
//
// case = Case (CurrentCulture): False
// case = Case (CurrentCultureIgnoreCase): True
// case = Case (InvariantCulture): False
// case = Case (InvariantCultureIgnoreCase): True
// case = Case (Ordinal): False
// case = Case (OrdinalIgnoreCase): True
此過載主要介紹下後兩個入參。
Boolean:布林型別入參,預設 false。true:忽略大小寫;false:區分大小寫。
CultureInfo:指定程式碼的區域性,允許為 null,但必須站位。為空時取當前區域(CultureInfo.CurrentCulture.CompareInfo)。
注:關於 CultureInfo 的詳細測試範例,詳見上一部分中的摺疊程式碼。
以下是當前過載的部分原始碼:
public string Replace(string oldValue, string? newValue, bool ignoreCase, CultureInfo? culture)
{
return ReplaceCore(oldValue, newValue, culture?.CompareInfo, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
private string ReplaceCore(string oldValue, string newValue, CompareInfo ci, CompareOptions options)
{
if ((object)oldValue == null)
{
throw new ArgumentNullException("oldValue");
}
if (oldValue.Length == 0)
{
throw new ArgumentException(SR.Argument_StringZeroLength, "oldValue");
}
return ReplaceCore(this, oldValue.AsSpan(), newValue.AsSpan(), ci ?? CultureInfo.CurrentCulture.CompareInfo, options) ?? this;
}
private static string ReplaceCore(ReadOnlySpan<char> searchSpace, ReadOnlySpan<char> oldValue, ReadOnlySpan<char> newValue, CompareInfo compareInfo, CompareOptions options)
{
Span<char> initialBuffer = stackalloc char[256];
ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer);
valueStringBuilder.EnsureCapacity(searchSpace.Length);
bool flag = false;
while (true)
{
int matchLength;
int num = compareInfo.IndexOf(searchSpace, oldValue, options, out matchLength);
if (num < 0 || matchLength == 0)
{
break;
}
valueStringBuilder.Append(searchSpace.Slice(0, num));
valueStringBuilder.Append(newValue);
searchSpace = searchSpace.Slice(num + matchLength);
flag = true;
}
if (!flag)
{
valueStringBuilder.Dispose();
return null;
}
valueStringBuilder.Append(searchSpace);
return valueStringBuilder.ToString();
}
在指定的輸入字串(input)內,使用指定的替換字串(replacement),替換與某個正規表示式模式(需要在範例化 Regex 物件時,將正規表示式傳入)匹配的所有的字串。
// 語法
public string Replace (string input, string replacement);
下面是一個簡單的範例:
// 目的是將多餘的空格去掉
string input = "This is text with far too much white space.";
string pattern = "\\s+"; // \s:匹配任何空白字元;+:匹配一次或多次
string replacement = " ";
Regex rgx = new Regex(pattern); // 範例化時傳入正規表示式
string result = rgx.Replace(input, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);
// 輸出結果:
// Original String: This is text with far too much white space.
// Replacement String: This is text with far too much white space.
在指定的輸入字串內(input),使用指定的替換字串(replacement)替換與指定正規表示式(pattern)匹配的所有字串。
// 語法:
public static string Replace (string input, string pattern, string replacement);
// 目的:將多餘的空格去掉
string input = "This is text with far too much white space.";
string pattern = "\\s+";
// 注:\s 匹配任何空白字元,包括空格、製表符、換頁符等
// 注:+ 重複一次或多次
string replacement = " "; // 將連續出現的多個空格,替換為一個
string result = Regex.Replace(input, pattern, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);
// 輸出結果:
//Original String: This is text with far too much white space.
//Replacement String: This is text with far too much white space.
在指定輸入子字串(input)內,使用指定替換字串(replacement)替換與某個正規表示式模式匹配的字串(其數目為指定的最大數目)。startat 是匹配開始的位置。
// 語法:
public string Replace (string input, string replacement, int count, int startat);
下面是一個範例:
// 目的:新增雙倍行距
string input = "Instantiating a New Type\n" +
"Generally, there are two ways that an\n" +
"instance of a class or structure can\n" +
"be instantiated. ";
Console.WriteLine("原內容:");
Console.WriteLine(input);
// .:匹配除‘\n’之外的任何單個字元;*:匹配零次或多次
string pattern = "^.*$"; // ^.*$ 在這裡就是匹配每一行中‘\n’前邊的字串
string replacement = "\n$&"; // 在匹配項前新增‘\n’;$&:代表匹配內容
Regex rgx = new Regex(pattern, RegexOptions.Multiline); // Multiline:多行模式,不僅僅在整個字串的開頭和結尾匹配
string result = string.Empty;
Match match = rgx.Match(input); // 判斷能否匹配
if (match.Success)
result = rgx.Replace(input,
replacement,
-1, // >= 0 時,就是匹配具體次數,= -1 時就是不限制次數
match.Index + match.Length + 1 // 作用就是跳過第一個匹配項(第一行不做處理)
// 當第一次匹配時:Index=0,length=除了‘\n’之外的長度,最後再 +1 就是第一行全部的內容
);
Console.WriteLine("結果內容:");
Console.WriteLine(result);
// 輸出結果:
// 原內容:
// Instantiating a New Type
// Generally, there are two ways that an
// instance of a class or structure can
// be instantiated.
// 結果內容:
// Instantiating a New Type
//
// Generally, there are two ways that an
//
// instance of a class or structure can
//
// be instantiated.
在入參字串(input)中,進行正規表示式(pattern)的匹配,匹配成功的,傳遞給 MatchEvaluator 委託(evaluator)處理完成後,替換原匹配值。
RegexOptions 為匹配操作設定項(關於 RegexOptions 詳見官網:RegexOptions 列舉),TimeSpan 為超時時間間隔。
public static string Replace (string input, string pattern,
System.Text.RegularExpressions.MatchEvaluator evaluator,
System.Text.RegularExpressions.RegexOptions options,
TimeSpan matchTimeout);
下面是一個範例:
// 目的:將輸入的每個單詞中的字母順序隨機打亂,再一起輸出
static void Main(string[] args)
{
string words = "letter alphabetical missing lack release " +
"penchant slack acryllic laundry cease";
string pattern = @"\w+ # Matches all the characters in a word.";
MatchEvaluator evaluator = new MatchEvaluator(WordScrambler); // WordScrambler:回撥函數
Console.WriteLine("Original words:");
Console.WriteLine(words);
Console.WriteLine();
try
{
Console.WriteLine("Scrambled words:");
Console.WriteLine(Regex.Replace(words, pattern, evaluator,
RegexOptions.IgnorePatternWhitespace, TimeSpan.FromSeconds(2)));
}
catch (RegexMatchTimeoutException)
{
Console.WriteLine("Word Scramble operation timed out.");
Console.WriteLine("Returned words:");
}
}
/// <summary>
/// 回撥:對全部匹配項逐一進行操作
/// </summary>
/// <param name="match"></param>
/// <returns></returns>
public static string WordScrambler(Match match)
{
int arraySize = match.Value.Length;
double[] keys = new double[arraySize]; // 存放亂數
char[] letters = new char[arraySize]; // 存放字母
Random rnd = new Random();
for (int ctr = 0; ctr < match.Value.Length; ctr++)
{
keys[ctr] = rnd.NextDouble(); // 生成亂數,用於重新排序
letters[ctr] = match.Value[ctr]; // 將輸入參單詞數拆解為字母陣列
}
Array.Sort(keys, letters, 0, arraySize, Comparer.Default); // 重新根據亂數大小排序
return new String(letters);
}
// 輸出結果:
// Original words:
// letter alphabetical missing lack release penchant slack acryllic laundry cease
//
// Scrambled words:
// eltetr aeplbtaiaclh ignisms lkac elsaree nchetapn acksl lcyaricl udarnly casee
string input = "Instantiating Instantiating Instantiating Instantiating";
Console.WriteLine("----原內容----");
Console.WriteLine(input);
string result = input.Replace("tiating","*******");
Console.WriteLine("----結果內容----");
Console.WriteLine(result);
// ----原內容----
// Instantiating Instantiating Instantiating Instantiating
// ----結果內容----
// Instan******* Instan******* Instan******* Instan*******
string input = "Instantiating Instantiating Instantiating Instantiating";
Console.WriteLine("----原內容----");
Console.WriteLine(input);
Regex regex = new Regex("tiating");
string result = regex.Replace(input, "*******",1);
Console.WriteLine("----結果內容----");
Console.WriteLine(result);
// ----原內容----
// Instantiating Instantiating Instantiating Instantiating
// ----結果內容----
// Instan******* Instantiating Instantiating Instantiating
string input = "Instantiating Instantiating Instantiating Instantiating";
Console.WriteLine("----原內容----");
Console.WriteLine(input);
Match match = Regex.Match(input, "tiating",RegexOptions.RightToLeft);
string first = input.Substring(0, match.Index);
string last = input.Length == first.Length + match.Length ? "" :
input.Substring(first.Length + match.Length,input.Length-(first.Length + match.Length));
string result = $"{first}*******{last}";
Console.WriteLine("----結果內容----");
Console.WriteLine(result);
// 兩次測試結果:
// ----原內容----
// Instantiating Instantiating Instantiating Instantiating 345
// ----結果內容----
// Instantiating Instantiating Instantiating Instan******* 345
// ----原內容----
// Instantiating Instantiating Instantiating Instantiating
// ----結果內容----
// Instantiating Instantiating Instantiating Instan*******
注:如有建議或疑問,歡迎留言。