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