2013-05-20 51 views
0

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

例如,

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

下面就让串密文是 “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乘3添加到int []中?我怎样才能避免使用小数,但使用1直?

对不起,我的英语不好。真的很感谢你的帮助,提前致谢。

回答

0

编辑。我曾建议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++; 
} 
+0

谢谢大家!!这是工作! 感谢gkovacs90给我建议一种方式,而Jimbo的解释,现在我完全了解它.. 并感谢loxxy建议我另一种方法.. =) –

1

我会用ciphertext[count] -'0'得到INT角色的价值。

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

1

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

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));