【问题标题】:How to replace a char with another char without using string.replace?如何在不使用 string.replace 的情况下用另一个字符替换一个字符?
【发布时间】:2019-07-06 13:46:39
【问题描述】:

我想为 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.Replace() ?
  • @BasilKosovan 因为这就是任务的方式,这就是我必须执行的方式,我已经说过我不应该使用 replace()。
  • @bimixbimix,我更新了我的答案,请查看。
  • @PrasadTelkikar 我想找到所有出现的“H”并用“p”更改所有这些。
  • 你可以看看我的回答

标签: c# string replace find


【解决方案1】:

使用 Linq 不使用 string.Replace() 的单线解决方案,

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 Fiddle

【讨论】:

  • 他想用其他字符串替换字符串而不是其他字符串中的字符
  • @AiverReaver,嘿,检查更新的答案,现在我的答案支持替换 string。看看我的回答
  • @AiverReaver,请查看 OP 提供的评论,他明确提到他想用 p 替换 H,即用另一个 char 替换 char
  • 只支持替换空格分隔的单词。 string.Replace 适用于任何子字符串。 "Hello".Replace("He", "Ro") 会给出“Rollo”,但您的代码不会。
  • @juharr,如果没有 linq 的单行 中的 string.replace(),您的场景很难替换,但我的回答支持 OP 的期望
【解决方案2】:

一般的方法首先使用String.IndexOf函数在其他字符串上找到要替换的字符串位置,然后将字符串从要替换的位置分割到要替换的字符串长度,而不是仅使用string.insert函数插入字符串。

【讨论】:

  • 可以替换字符串吗?您的解决方案仅替换一个字符。
  • 能否请您提供实现,而不仅仅是声明,如果您使用小提琴提供正确的实现,我将投票赞成
猜你喜欢
  • 2020-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-21
  • 1970-01-01
  • 2013-12-03
  • 2021-06-15
  • 1970-01-01
相关资源
最近更新 更多