Home > Net >  Splitting a string every 4th character and insert a dash(-). I want to return a new string with the
Splitting a string every 4th character and insert a dash(-). I want to return a new string with the

Time:12-23

I want to split a string every 4th character, as I am creating generating a credit card number. I want to return a new string that contains the format specified.

char accountNumber[] = "1234123412341234"; 

// expected output: 1234-1234-1234-1234

CodePudding user response:

There are many ways, this is a one.

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

char* split(char *s) {
    const int MAX_LEN = 100;
    char *r = malloc(MAX_LEN * sizeof(char));

    int len = strlen(s), i = 0;
    for (i = 0; i < len; i  ) {
        if (i % 4 == 0 && i > 0) {
            char* c = "-";
            strncat(r, c, sizeof(char));
        }
        strncat(r, s   i, sizeof(char));
    }
    return r;
}

int main() {
    puts(split("1234123412341234"));
}

CodePudding user response:

char accountNumber[] = "1234123412341234";

int n = 16;//the length of old string;
char newStr[n   (n / 4)];//the length of new string;

for (int i = 0, j = 0; i < n; i  , j  )
{
    newStr[j] = accountNumber[i];
    if ((i   1) % 4 == 0)
    {
        if (i != (n - 1))
        {
            //If i is an integer multiple of 4, and i is not the last one, insert '-' after it;
            j  ;
            newStr[j] = '-';
        }
        else
        {
            //If i is the last one, insert '\0' to indicate the end of the string
            j  ;
            newStr[j] = '\0';
        }
    }
}
printf("%s", newStr);
  • Related