[英]Convert “int” into “char” inside char array
我正在嘗試進行字符串操作。 這是我的C#代碼:
static void Main(string[] args)
{
string input;
string output;
int length;
Console.WriteLine("input = ");
input = Console.ReadLine();
length = input.Length;
if ((input != "") || (length != 0))
{
Random randem = new Random();
int i = -1; //because I do not want the first number to be replaced by the random number
char[] characters = input.ToCharArray();
while (i < length)
{
int num = randem.Next(0, 9);
char num1 = Convert.ToChar(num);
i = i + 2; //so that every next character will be replaced by random number.. :D
characters[i] = num1; //*error* here
}
output = new string(characters);
Console.WriteLine(output);
}
例如:
用戶輸入: "i_love_to_eat_fish"
所需的輸出: "i2l4v1_9o5e8t7f8s2"
請注意,在char []字符中唯一不變的字符是:“ ilv _ oetfs”。 (程序的期望輸出)
我已經嘗試過使用此代碼,但是仍然會在characters[i] = num1
處繼續出錯。
我在正確的軌道上嗎?
無論何時你來到i = 17
加2, i
。 這使得i = 19
,輸入長度等於18,這導致超出范圍的異常。
我猜你得到的錯誤是IndexOutOfRangeException
這是因為i = i + 2;
。 while
可以確保i
小於length
,但是再加上2可能會導致i
大於length
。 只需添加一條支票,證明支票沒有超出length
。
i = i + 2;
if(i < length)
characters[i] = num1;
或者只是更改為for
循環。
Random randem = new Random();
char[] characters = input.ToCharArray();
for(int i = 1; i < length; i += 2)
{
int num = randem.Next(1, 10); // max value is exclusive
char num1 = num.ToString()[0];
characters[i] = num1;
}
output = new string(characters);
Console.WriteLine(output);
就像Shar1er80指出的那樣,您當前正在將數字轉換為具有相同ASCII值的char
,而不是表示數字的實際字符。 數字0-9由值48-57表示。 您可以將呼叫更改為Random.Next
,將其更改為:
int num = randem.Next(48, 58); // The upper bound is exclusive, not inclusive
char num1 = (char)num;
或者像Shar1er80那樣
int num = randem.Next(0,10) // Assumming you want digits 0-9
char num1 = num.ToString[0];
還要注意, Random.Next
的最大值是唯一的,因此,如果要包括使用9的可能性,則必須使用比所需的最大值大1的上限。
這是因為您從索引-1開始,並且字符不包含索引-1。
編輯:對不起沒有正確的答案,它必須是while(i < length - 2)
您遇到的錯誤是IndexOutOfTheRangeException
,它本身解釋了一切。
這意味着循環中要饋入數組的索引超出了其length-1
(因為數組具有從0開始的索引)
因此,當您執行i+2
,您需要在任何時間檢查i+2
是否不超過i.length-1
。 在你的循環中。
通常,只需檢查您是否提供0 and Array.Length-1
之間的索引
更改此行
char num1 = Convert.ToChar(num);
至
char num1 = num.ToString()[0];
那...放
characters[i] = num1;
在if塊中
if (i < length)
characters[i] = num1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.