【问题标题】:Using .Replace to replace a oldValue with a newValue使用 .Replace 将 oldValue 替换为 newValue
【发布时间】:2013-03-06 17:49:38
【问题描述】:

我在使用 .replace 替换字符时遇到了一些问题

例子:

string word = "Hello";
oldValue = "H";
newValue = "A"; 

word = word.replace(oldValue,newValue)

上面的代码运行良好,H 将替换为 A,输出将是 Aello

现在我想使用更多的 newValue 而不仅仅是一个,所以 H 可以替换为随机的 newValue 而不仅仅是“A”

当我更改 newValue 时:

newValue = 'A', 'B', 'C';

.Replace 函数给我一个错误

【问题讨论】:

  • 你想随机替换吗? :)
  • 你能重构你的代码吗?这甚至不是有效的 C# 代码
  • 是的,我不知道 newValue 是什么,随机字符。

标签: c# string-formatting


【解决方案1】:

尝试使用System.Random 类在newValue 数组中获取随机项。

string word = "Hello";
var rand = new System.Random();
var oldValue = "H";
var newValue = new[] { "A", "B", "C" };

word = word.Replace(oldValue, newValue[rand.Next(0, 2)]);

【讨论】:

  • 你快了 10 秒 :)
  • 您选择一个 0 或 1 的随机数,因此它永远不会替换为 "C"
【解决方案2】:

Replace 方法不支持随机替换,需要自己实现随机部分。

Replace 方法也不支持替换回调,但 Regex.Replace 方法支持:

string word = "Hello Hello Hello";
Random rnd = new Random();
string[] newValue = { "A", "B", "C" };
word = Regex.Replace(word, "H", m => newValue[rnd.Next(newValue.Length)]);

Console.WriteLine(word);

示例输出:

Cello Bello Aello

【讨论】:

  • 出于好奇,使用string.Replace 或使用正则表达式哪个更快?
  • @Kane:String.Replace 方法自然更快,但不支持替换回调。
  • 酷,谢谢 - 这可能看起来很奇怪,但我真的不知道哪个更快,而且懒得做任何基准测试。
【解决方案3】:

您可以使用随机字符串创建方法并通过替换推送它: Random String Generator Returning Same String

【讨论】:

    【解决方案4】:

    用 A-Z 之间的随机大写字母 (65-90) 替换。

    string oldValue = "H";
    
    string newValue = Convert.ToString((char)(new Random().Next(65, 91)));
    word.Replace(oldValue, newValue);
    

    【讨论】:

      【解决方案5】:

      有趣的任务,但就是这样:)

      string word = "Hello";
      char[] repl = {'A', 'B', 'C'};
      Random rnd = new Random();
      int ind = rnd.Next(0, repl.Length);
      
      word = word.Replace('H', repl[ind]);
      

      编辑:rnd.Next 的 maxValue 是独占的,因此您应该使用 repl.Length 而不是 (repl.Length -1)

      【讨论】:

        猜你喜欢
        • 2015-08-02
        • 2018-07-27
        • 2021-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多