user15183233
user15183233

Reputation:

Remove multiple characters from string

I'm trying to creat a program that removes all occurences from a character that I choose from a certain string and also returs the number of characters that were removed.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define DIMV 10



int eliminar(char texto[], char ch, char novoTexto[]){
int a=0,i;

for(i=0; texto[i] != '\0';i++){
    texto[i] = texto[i+a];
    novoTexto[i]=texto[i];
        if(novoTexto[i]==ch){
            novoTexto[i] = '\0';
        a++;
        }
}

return a;
}


int main()
 {
 char frase[]="Uma arara torta!";
 char res[50];

 printf("%s\n",frase);
 printf("%d\n",eliminar(frase,'r',res));
 printf("%s\n",res);
 return 0;
 }

When I run the program, it returns:

Uma arara torta!                                                                                                                                
3                                                                                                                                               
Uma a 

What I wanted to return is:

Uma arara torta!                                                                                                                                
3                                                                                                                                               
Uma aaa tota! 

It's a silly question but I can't find the mistake that I made. Thank you!

Upvotes: 0

Views: 881

Answers (2)

MKali
MKali

Reputation: 11

Putting '\0' means to terminate the string there. check this:

int eliminator(char * texto, char ch, char * novoTexto) {
    int i=0;
    while(*texto != '\0') {
        if (*texto == ch) {
            texto++;
            ++i;
        } else {
            *novoTexto++ = *texto++;
        }
    }
    *novoTexto = '\0';
    return i;
}

int main(int arg, char **argv) {
    char frase[] = "Uma arara torta!";
    char res[50];

    printf("%s\n",frase);
    printf("%d\n",eliminator(frase, 'r', res));
    printf("%s\n",res);   
}

Upvotes: 0

MikeCAT
MikeCAT

Reputation: 75062

Putting '\0' means to terminate the string there.

You have to skip adding characters to eliminate.

Try this:

int eliminar(char texto[], char ch, char novoTexto[]){
    int a=0,i,j=0;

    for(i=0; texto[i] != '\0';i++){
        if(texto[i]==ch){
            a++;
        }else{
            novoTexto[j]=texto[i];
            j++;
        }
    }
    novoTexto[j]='\0';

    return a;
}

Upvotes: 3

Related Questions