![](/img/trans.png)
[英]Is there an easier way to format a string with an exact length in C#?
[英]Best way to replace string with random values exact length c#
我正在尋找用隨機值替換字符串 - 並保持相同的長度。 但是,我希望將所有字符替換為字符,將數字替換為數字。
我想知道最好的方法來做到這一點。 我正在考慮對每個字符進行 for 循環,但這可能會非常消耗性能。
我可能是錯的,在這種情況下請告訴我。
謝謝
除非您有性能要求和/或問題,否則不要進行微優化。 只需使用一個循環。
你錯了。 要知道它是字符還是數字,您需要查看字符串中的每個值,因此無論如何都需要遍歷字符串。
如果不循環遍歷每個角色,你還打算怎么做? 至少,您需要查看字符是否為數字並替換它。 我假設你可以制作一個名為 RandomChar 和 RandomDigit 的 function。 這將比 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 留給讀者作為練習。
如果它是一個長字符串,則可能是因為對字符串的更改會導致創建新的 object。 我會使用 for 循環,但將您的字符串轉換為 char 數組操作,然后再轉換回字符串。
(我假設您已經有了生成隨機字符的方法。)
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();
考慮使用 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(); }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.