How to change a name of a string

0

I am making a question in uri tag replacement , which has to be replaced one name for another but I'm not having success, I can only get normal names with no 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);
}
    
asked by anonymous 12.06.2018 / 18:34

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, "
Entrada: O rato roeu a roupa do rei de Roma!
Saida: O rato roeu a roupa do rei de Paris!
" ); 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; }

Output:

#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, "
Entrada: O rato roeu a roupa do rei de Roma!
Saida: O rato roeu a roupa do rei de Paris!
" ); 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; }
    
12.06.2018 / 20:06