Home > database >  Add string to specific position
Add string to specific position

Time:04-03

I'm fairly new to C, I have an encoding rule that is basicaly, if there is Z in the string, we add another Z, if there are no Z, just repeat

Example

input: STZCK -> output: STZZCK

I managed to add another Z but just at the end of string, I have to add after the found one.

I tried

char * encoding (char * str){
    
    int size = strlen(str);

    for(int i=0; i<size; i  ){
    
        if(str[i] == 'Z'){

            char ch = 'Z';
            strncat(str, &ch, 1);

        }
        else if(str[i] != 'Z'){
            str[i] = str[i];
        }
    }
    
    return str;
}

Thanks in advance

CodePudding user response:

You need to clarify if your function receives a buffer with enough space for the output string or if your function needs to dynamically allocate memory.

In the first case you can do it like this:

#include <stdio.h>

void encode(char *d, const char *s)
{
    do {
        *d   = *s;
        if (*s == 'Z') {
            *d   = *s;
        }
    } while (*s   != 0);
}

int main(void) {
    char *src[] = {"STZCK", "HELLO", "ZZ", "", NULL};
    char dst[256];
    
    for (char **s = src; *s != NULL;   s) {
        encode(dst, *s);
        printf("%s -> %s\n", *s, dst);
    }
    
    return 0;
}

CodePudding user response:

I would do it like this

 char* encoding(char* str) {
    int len = strlen(str);

    // count Z to see how much bigger the result will be 
    int countZ = 0;
    for (int i = 0; i < len; i  ) {
        if (str[i] == 'Z') countZ  ;
    }
    // make return string large enough
    char* retStr = malloc(len   countZ   1);

    // copy old to new with added Zs  
    int retOff = 0;
    for (int i = 0; i < len; i  ) {
        retStr[retOff  ] = str[i];
        if (str[i] == 'Z') retStr[retOff  ] = 'Z';
    }
    retStr[retOff] = 0;
    return retStr;
}
  • Related