How to replace a middle character of a string and swap for two characters?

Asked

Viewed 1,074 times

0

For example,

Char s1 [  ] = "azul";
 Char S2 [ ] = "z";
Char S3 [ ] = "PP";

Puts(s1); //azul

Code to replace...

Expected result:

Puts(s1); //aPPul

Note: I was able to change 1 character by another, but 1 by 2 and still keep the subsequent characters, no.

  • what is the type Chris?

  • It’s like char, I fixed it in editing.

1 answer

1


There is no escape: you will have to allocate another place to store your result. By doing this you can then replace your string and have enough space to store it all:

char *
substituir(char * original, char busca, char * subst) {
    int i, num_inst;
    char * ptr, * ptr2, * resultado;

    /* conta o número de instâncias de busca em original */
    for (ptr = original, num_inst = 0; *ptr; ptr ++) {
        if (*ptr == busca) num_inst ++;
    }
    /* aloca memória suficiente para guardar o resultado */
    resultado = malloc(
        strlen(original)/* letras no original */
        + (strlen(subst) - 1) * num_inst /* número de caracteres extra para caberem as instâncias de subst */
        + 1 /* para o '\0' final */
    );
    if (resultado == NULL) return resultado; /* se não conseguiu alocar memória, retorne */
    for (ptr = original, ptr2 = resultado;
         * ptr; ) {
        if (*ptr == busca) {
            /* concatene a sequência de substituição e depois ache o fim da string */
            strcat(ptr2, subst);
            while (* ptr2) ptr2 ++;
            ptr ++; // tem que avançar o ponteiro de original, também
        } else {
            /* copie o byte */
            *ptr2 ++ = *ptr ++;
        }
    }
    * ptr2 = '\0';

    return resultado;
}

Note that the above code allocates a string new, so if you’re going to replace the old one and it’s dynamically allocated, remember to call free() in it! Note also that original has not been touched and remains with the original value.

  • Wtmute, thanks for the tip. But I have one question: what is the logic in the first "go" for the stop condition to be "*ptr"?

  • 1

    *ptr, as you know, dereferences the pointer, that is, brings the value stored in the memory address pointed by ptr. When a value comes without a logical operator like == or <, is equivalent to testing if it is non-zero. Like strings in C always end with the zero character ('\0'), This is equivalent to stopping when it comes to the end of the string. It’s a very idiomatic construct in C.

  • I understood and really liked the tip. From now on I will try to find other situation to use.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.