日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#?Replace替換的具體使用_C#教程

作者:橙子家 ? 更新時間: 2023-05-21 編程語言

前言

Replace 的作用就是,通過指定內容的替換,返回一個新字符串。

返回值中,已將當前字符串中的指定 Unicode 字符或 String 的?所有匹配項,替換為指定的新的 Unicode 字符或 String。

一、String.Replace() 的幾個重載

String.Replace() 總共有四個重載,分別是:(詳見官網:String.Replace 方法)

  • Replace(Char, Char)、
  • Replace(String, String)、
  • Replace(String, String, StringComparison)、
  • Replace(String, String, Boolean, CultureInfo)。

下面來逐個簡單介紹下。

1、Replace(Char, Char)

// 作用:
// 將實例中出現的所有指定 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 整型類型。

2、String.Replace(String, String)

// 作用:
// 實例中出現的所有指定字符串都替換為另一個指定的字符串
// 語法:
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'

?3、Replace(String, String, StringComparison)

相較于上一個重載,新增了一個入參枚舉類型 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

4、Replace(String, String, Boolean, CultureInfo)

此重載主要介紹下后兩個入參。

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();
}

二、Regex.Replace() 的幾個常用重載

1、Replace(String, String)

在指定的輸入字符串(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.

?2、Replace(String, String, String)

在指定的輸入字符串內(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.

3、Replace(String, String, Int32, Int32)

在指定輸入子字符串(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.

4、Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan)

在入參字符串(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

三、關于 Replace 的實際需求簡單示例

1、全部替換匹配項

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*******

2、僅替換第一個匹配項

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

3、僅替換最后一個匹配項

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*******

參考:String.Replace 方法

??? ?Regex.Replace 方法

原文鏈接:https://www.cnblogs.com/czzj/p/ReplaceInfo.html

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新