将字符串拆分为C中的数组

时间:2015-11-06 23:49:10

标签: c arrays

int main() 
{
    int longNum = 12345, tempNum[5], i;
    for (i = 0; i <= 5; i++)
    {
        tempNum[i] = longNum[i] ; // not valid, how do i make this work?
    }
    printf("%d\n", tempNum);
    return 0;
}

我试图浏览longNum的所有数字并将它们推入tempNum []。

4 个答案:

答案 0 :(得分:1)

您可以尝试使用模运算符:

int main() 
{
    int longNum = 12345, tempNum[5], i;

    for (i = 4; i >= 0; i--)
    {
        tempNum[i] = longNum % 10;
        longNum /= 10;
    }

    for( i = 0; i < 5; i++ )
    {
        printf("%d\n", tempNum[i]);
    }
    return 0;
}

答案 1 :(得分:0)

对于动态长度:

#include <stdio.h>
#include <stdlib.h>

int main() 
{
    long long longNum = 1234512345;  // can be any size within `long long` limit.
    int tempNum[5], i;

    int num_digits = 0;
    long temp = longNum;
    while( temp > 0 )
    {
        temp /= 10;
        num_digits++;
    }
    printf( "num_digits = %d\n", num_digits );

    // Allocate dynamic array.
    int *pos = malloc( num_digits * sizeof( int ) );

    for( i = num_digits - 1; i >= 0; i-- )
    {
        pos[i] = longNum % 10;
        longNum /= 10;
    }

    for( i = 0; i < num_digits; i++ )
    {
        printf("%d\n", pos[i]);
    }

    return 0;
}

答案 2 :(得分:0)

你可以试试这个:

int main(  )
{
  int longNum = 12345, tempNum[5], i;
  char numstr[99];

  itoa( longNum, numstr, 10 );

  for ( i = 0; i < 5; i++ )
{
    tempNum[i]=numstr[i] - '0';
    printf( "\n%d", tempNum[i] );
}

  return 0;
}

答案 3 :(得分:0)

#include <stdio.h>
int main()
{
    int longNum = 12345, tempNum[5], i;
    for (i = 1; i <= 5; i++)
    {
        tempNum[5-i] = longNum % 10;
        longNum = longNum/10;
    }
    printf("%d%d%d%d%d\n", tempNum[0], tempNum[1], tempNum[2], tempNum[3], tempNum[4]);
    return 0;
}