【问题标题】:Append int in string to int[]将字符串中的 int 附加到 int[]
【发布时间】:2013-05-20 17:26:16
【问题描述】:

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

例如,

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 x 3 附加到 int[] 中?如何避免使用小数而直接使用 1?

对不起,我的英语不好。非常感谢您的帮助,在此先感谢。

【问题讨论】:

    标签: string winforms visual-c++ int


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      其他人指出了您的错误。另外,要不要这样呢?

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

      【讨论】:

        【解决方案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++;
        }
        

        【讨论】:

        • 谢谢大家!!成功了!感谢 gkovacs90 为我建议一种方法,而 Jimbo 的解释,现在我完全理解它了.. 并感谢 loxxy 建议我另一种方法..=)
        猜你喜欢
        • 2020-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-09
        • 2015-04-22
        相关资源
        最近更新 更多