How to change a string name

Asked

Viewed 263 times

0

I’m asking a question in Rio Tag replacement, that one has to replace one name with another but I’m not succeeding, I can only with normal names without characters

My code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
  char nome[] = "Stack overflow";
  char *ptr;
  char aux[900];
  int cont = 0;
  ptr = strtok(nome, " ");
  while(ptr != NULL)
  {
    if(cont == 0)
    {
        if(strcmp(ptr, "overflow") == 0)
        {
            strcpy(aux, "certo");
        }
        else
        {
            strcpy(aux, ptr);
            strcat(aux, " ");
        }
        cont++;
    }
    else
    {
        if(strcmp(ptr, "overflow") == 0)
        {
            strcat(aux, "certo");
        }
        else
        {
            strcat(aux, ptr);
            strcat(aux, " ");
        }
    }
    ptr = strtok(NULL, " ");
}
   puts(aux);
}
  • Where’s the part you play tag or not tag ? Personally I find it easier to iterate the characters normally instead of using strtok, and generate an output buffer with just the right characters, and then just show

  • As I would change name, I tried to do a by passing the sentence with what was to be changed but other parts of the text were changed

1 answer

1


To replace all the strings contained in a string, you can implement something like:

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

int strrepstr( char * dst, const char * src, const char * oldstr, const char * newstr )
{
    char * p = NULL;
    char * aux = NULL;
    int oldstrlen = 0;
    int count = 0;

    if( !dst || !src || !oldstr || !newstr )
        return -1;

    oldstrlen = strlen( oldstr );

    if( !oldstrlen )
        return -1;

    p = strstr( src, oldstr );
    aux = (char*) src;

    strcpy( dst, "\0" );

    while( p )
    {
        strncat( dst, aux, p - aux );

        strcat( dst, newstr );
        count++;

        p += oldstrlen;
        aux = p;

        p = strstr( aux, oldstr );
    }

    strcat( dst, aux );

    return count;
}

char main( void )
{
    char entrada[] = "O rato roeu a roupa do rei de Roma!";
    char saida[100];

    strrepstr( saida, entrada, "Roma", "Paris" );

    printf("Entrada: %s\n", entrada );
    printf("Saida: %s\n", saida );

    return 0;
}

Exit:

Entrada: O rato roeu a roupa do rei de Roma!
Saida: O rato roeu a roupa do rei de Paris!

Browser other questions tagged

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