繁体   English   中英

在字符串中将int追加到int []

[英]Append int in string to int[]

假设有一个字符串“123124125”。 我希望从字符串中取出每3个字符并存储到整数数组中。

例如,

int[0] = 123,
int[1] = 124,
int[2] = 125,

让下面的String密文是“123124125”:

String ^ ciphertext;
int length1 = ciphertext-> Length;
int count = 0;
int count1 = 0;

while (count < length1)
{
    number[count1] = (ciphertext[count] * 100) + (ciphertext[count+1] * 10) + ciphertext[count+2]);
    count = count + 3;
    count1++;
}

以上是我写的代码。 结果应该是number[]内的123,但不是。

ciphertext[count]乘以100时,它不会使用'1'乘以100,而是十进制数。 因此,十进制中的“1”为“50”,因此结果为“5000”而不是100。

我的问题是如何将它们3 by 3追加到int []中? 如何避免使用小数而使用1?

对不起,我的英语不好。 非常感谢您的帮助,提前感谢。

我会使用ciphertext[count] -'0'来获取字符的int值。

您还可以在要转换为整数的子字符串上使用atoi函数。

其他人指出了你的错误。 此外,这样做怎么样?

string str = "123124125"; 

int i = str.Length / 3;

int[] number = new int[i];

while(--i>=0) number[i] = int.Parse(str.Substring(i*3,3));

编辑。 我曾建议使用9 - ('9' - char),但正如gkovacs90在他的回答中建议的那样,char - '0'是更好的写作方式。

原因是ciphertext[count]是一个字符,因此将其转换为int会为您提供该字符的ascii代码而不是整数。 你可以做一些像ciphertext[count]) -'0'

例如,假设ciphertext[count] is '1' 字符1的ascii值为49(请参阅http://www.asciitable.com/ )。 因此,如果你做ciphertext[count]*100会给你4900。

但是如果你做ciphertext[count] -'0'你会得到49 - 48 == 1

所以...

String ciphertext;
int length1 = ciphertext-> Length;
int count = 0;
int count1 = 0;

while (count < length1)
{
    number[count1] = 
        ((ciphertext[count] -'0') * 100) + 
        ((ciphertext[count+1] - '0') * 10) + 
        (ciphertext[count+2] - '0');
    count = count + 3;
    count1++;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM