Home > Mobile >  Inserting a character into a char array
Inserting a character into a char array

Time:11-08

I have a char array containing a number.

char number[] = "12000000"

I need to have a function to insert a divider in every 3 digits. Like:

char result[] = "12,000,000"

My function accepts the number as a char pointer and it needs to return result as a char pointer too.

  char* insert_divider(char* number) {

    some magic;
    return result;
  } 

I have no idea of working with pointers. Thanks.

CodePudding user response:

Here you have a function that adds char c every num characters starting from the end. You need to make sure that the string buffer is long enough to accommodate the amended string.

char *addEvery(char *str, char c, unsigned num)
{
    char *end = str;

    if(str && *str && num)
    {
        size_t count = 1;
        while(*(end)) end  ;
        while(end != str)
        {
            end--;
            count  ;
            if(!(count % (num   1)) && str != end)
            {
                memmove(end   1, end, count);
                *end = c;
                count  ;
            }
        }
    }
    return str;
}

int main(void)
{
    char str[100] = "120000000000";
    printf("%s", addEvery(str,',',3));
}

CodePudding user response:

I came up with this piece of code:

  char *result;
  result = (char*) malloc(15);
  int len= strlen(input);
  uint8_t cursor= 0;
  for(int i = 0; i < len; i  ) {
    if ((len- i) > 0 && (len- i) % 3 == 0) {
      result[i   cursor] = ',';
      cursor  ;
    }
    result[i   cursor] = input[i];
  }
  result[len  cursor] = '\0';

Thanks everyone for help and advice.

CodePudding user response:

Here is another way to do it:

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

char* insert_divider(char* number, size_t length) {
    int j = length   length/3; // every 3 digits a ',' will be inserted
    char *out = (char*)malloc(j   1);

    out[j--] = '\0';

    for (int i = length - 1, k = 1; i >= 0; i--, k  ) {
        out[j--] = number[i];
        if ((k%3) == 0) {
            out[j--] = ',';
        }
    }

    return out;
}

int main(){
    char number[] = "12000000";
    char *outNumber = insert_divider(number, strlen(number));
    printf("%s", outNumber);
    free(outNumber);
    return 0;
}
  • Related