簡體   English   中英

如何在不使用 string.replace 的情況下用另一個字符替換一個字符?

[英]How to replace a char with another char without using string.replace?

我想為 ex 找到所有出現的字符。 較長字符串“The Haunting of Hill House”中的“H”。 我正在使用此代碼,但我只是按特定位置搜索。

 static void Main(string[] args)
    {
        string str = "The Haunting of Hill House!";
       Console.WriteLine("String: " + str);
        // replacing character at position 7
        int pos = 7;
        char rep = 'p';


            string res = str.Substring(0, pos) + rep + str.Substring(pos + 1);
            Console.WriteLine("String after replacing a character: " + res);
            Console.ReadLine();

    }

一般方法首先使用String.IndexOf函數找到要在其他字符串上替換的字符串位置,然后將字符串從要替換的字符串的位置到長度進行切片,而不僅僅是使用string.insert函數插入字符串。

使用 Linq 而不使用string.Replace() One Line 解決方案,

string result = string.Join("", str.Select(x => x == 'H' ? 'p' : x));
                                                       `

如果你想替換整個字符串然后試試這個

string result1 = string.Join(" ", str.Split(' ').Select(x => x == "Hill" ? "Zill" : x));

輸入:

The Haunting of Hill House!

輸出:

The paunting of pill pouse!

The Haunting of Zill House!
              //^^^^ Replaced word from Hill to Zill 

.net 小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM