0

I have 2 functions, they are called SplitInt(unsigned int x) and SplitChar(char x[])

SplitInt takes in any positive integer, such as 12345, and puts each digit into an integer array, but backwards. So for SplitInt(12345) the array would look like this:

array[0] = 5
array[1] = 4
array[2] = 3
array[3] = 2
array[4] = 1

SplitChar() is supposed to do the same thing but take in a C-Style string, such as "12345".

How would I separate the individual digits and send them into an integer array? I am not allowed to use string class.

Thanks!

3
  • 3
    What have you tried so far? Also, remember that a c-style string is just a char array and that 1 = '1' - '0' Commented Nov 16, 2016 at 4:23
  • Nothing to be honest. I only understand how to do it with integers being passed in because I just used modulus to separate the number to individual digits. For the string, I know conceptually what I wanna do. "123456789" gets passed in, I look at the first character, send it into the array, then second character, send it into array, and so on. Don't know the syntax to get that done though. Commented Nov 16, 2016 at 4:58
  • Is my function declaration correct? What I want to be able to do is this: SplitChar("123456789"); Commented Nov 16, 2016 at 5:01

1 Answer 1

1
#define MAX_STR_LENGTH 100

int array[MAX_STR_LENGTH];

int SplitChar(char x[])
{
    int len = strlen( x );

    if ( len > MAX_STR_LENGTH )
        return -1;

    int i = 0;

    while ( i < len )
    {
        array[len-i-1] = x[i] - '0';
        i++;
    }

    return len;
}

Returns the length of the string or -1 if too long.

Sign up to request clarification or add additional context in comments.

2 Comments

@acraig5075 Thanks, fixed
If you're going to provide free code, at least make it behave better than triggering UB when the input is too big...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.