2013-05-20 52 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));