I have a string:
012345678901234567890
I want it to broken into chunks of 7, like this:
0123456-7890123-4567890
I wrote this code:
strcpy(input,"01");
strcat(input,"2345678901234567890");
printf("input is %s\n",input);
char *output = malloc(22 * sizeof(char));
int i = 0;
for (char* c = input; *c != '\0'; c ) {
output[i] = *c;
if (i > 0 && (i % 7 == 0)) {
i ;
output[i] = '-';
}
i ;
}
output[i] = '\0';
printf("output is %s\n",output);
The output is this:
input is 012345678901234567890
output is 01234567-890123-456789-0
The problem is complicated by the fact that the pointer is counted from zero. Where is the error in my pointer logic? How can make the code work for an arbitrary number of septets?
EDIT
Here is my solution. Is there a cleaner way?
char *input = (char*) malloc(22 * sizeof(char*));
strcpy(input,"01");
strcat(input,"2345678901234567890");
printf("input is %s\n",input);
int i = 0;
int j = 0;
char *output = malloc(22 * sizeof(char));
for (char* c = input; *c != '\0'; c ) {
output[i] = *c;
j ;
if (j % 7 == 0 && i <22) {
i ;
output[i] = '-';
j = 0;
}
i ;
}
CodePudding user response:
For one thing, you are not allocating enough memory for the output
. You need to allocate room for 21 chars for copying chars from input
, 2 for the new dashes being inserted, 1 for the null terminator. That is 24 chars needed, but you are allocating room for only 22 chars.
Also, you are using one variable i
for two different purposes - indexing into input
and indexing into output
. The insertion of the dashes will offset the indexing into output
, which is the root problem with your code. So you need to use two separate variables instead.
Try this:
char *input = malloc(22 * sizeof(char*));
strcpy(input, "01");
strcat(input, "2345678901234567890");
printf("input is %s\n", input);
int input_len = strlen(input);
char *output = malloc((input_len ((input_len - 1) / 7) 1) * sizeof(char));
int j = 0;
for (int i = 0; i < input_len; i) {
if (i > 0 && i % 7 == 0) {
output[j ] = '-';
}
output[j ] = input[i];
}
output[j] = '\0';
printf("output is %s\n", output);