1

我正在寻找用随机值替换字符串 - 并保持相同的长度。但是,我希望将所有字符替换为字符,将数字替换为数字。

我想知道最好的方法来做到这一点。我正在考虑对每个字符进行 for 循环,但这可能会非常消耗性能。

我可能是错的,在这种情况下请告诉我。

谢谢

4

6 回答 6

2

除非您有性能要求和/或问题,否则不要进行微优化。只需使用一个循环。

于 2011-05-26T16:33:12.697 回答
2

你错了。要知道它是字符还是数字,您需要查看字符串中的每个值,因此无论如何都需要遍历字符串。

于 2011-05-26T16:33:47.753 回答
1

如果不循环遍历每个角色,你还打算怎么做?至少,您需要查看字符是否为数字并替换它。我假设您可以创建一个名为 RandomChar 和 RandomDigit 的函数。这将比 c# ish 写得更多 c++ ish,但你明白了:

for (int i=0;i<myStr.Length();++i)
{
  c=myStr[i];
  if(isDigit(c)) 
  {
    c=RandomDigit();
  }
  else
  {
    c=RandomChar();
  }
  myStr[i]=c;
}

真的没有其他办法,因为无论如何你都需要检查每个角色。

函数 isDigit、RandomDigit 和 RandomChar 留给读者作为练习。

于 2011-05-26T16:35:29.093 回答
1

如果它是一个长字符串,则可能是因为对字符串的更改会导致创建一个新对象。我会使用 for 循环,但将您的字符串转换为 char 数组操作,然后再转换回字符串。

于 2011-05-26T16:35:51.360 回答
0

(我假设您已经有了生成随机字符的方法。)

var source = "RUOKICU4T";
var builder = new StringBuilder(source.Length);

for (int index = 0; index < builder.Length; index += 1)
{
    if (Char.IsDigit(source[index]))
    {
        builder[index] = GetRandomDigit();
    }
    else if (Char.IsLetter(source[index]))
    {
        builder[index] = GetRandomLetter();
    }
}

string result = builder.ToString();
于 2011-05-26T16:48:47.757 回答
0

考虑使用 LINQ 来帮助避免显式循环。您可以重构以确保数字

static void Main()
{
    string value = "She sells 2008 sea shells by the (foozball)";

    string foo = string.Join("", value
                                .ToList()
                                .Select(x => GetRand(x))
                                );
    Console.WriteLine(foo);
    Console.Read();
}


private static string GetRand(char x)
{             
    int asc = Convert.ToInt16(x);            
    if (asc >= 48 && asc <= 57)
    {
        //get a digit
        return  (Convert.ToInt16(Path.GetRandomFileName()[0]) % 10).ToString();       
    }
    else if ((asc >= 65 && asc <= 90)
          || (asc >= 97 && asc <= 122))
    {
        //get a char
        return Path.GetRandomFileName().FirstOrDefault(n => Convert.ToInt16(n) >= 65).ToString();
    }
    else
    { return x.ToString(); }
}
于 2011-05-26T17:26:57.820 回答