How to create a function that deletes all spaces before and after the phrase starts in a string

Asked

Viewed 32 times

0

My goal in this function is to have a void function that changes a string so as to cut all spaces before and after the sentence, for example: transform the string " I went shopping " in the string "I went shopping". My current result is to receive exactly the same string I started with.

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

void trimmer(char frase[]){
int i=0,a=0,p=0,b=0,posb, len;
len=strlen(frase);
    while(b=0)  {
        if(frase[len-i] = ' '){
            i=i+1;
        }else
            {
            posb= len-i;
            printf("%i", posb);
            b=1;

        }
    }

    while(p <= posb, p++){
        if(frase[i] != ' ') {
                a=1;

         }
         if(a=1){
                frase[p]= frase[i];
                i++;
                p++;

        }

    }

}

int main(){
 char frase[]="    Eu nao fui a escola!    ";
 printf("%s %lu\n",frase,strlen(frase));
 trimmer(frase);
 printf("%s %lu\n",frase,strlen(frase));
 return 0;
}
  • What you have already achieved and what you have achieved so far?

  • I forgot, I’ve already updated.

1 answer

1


Bernard a first apparent error is the comparison using only a sign of =. The condition if(a=1) always returns true, and that’s where you copy the character, so the return is equal.

I did another implementation of its function trimmer. Not the most efficient but easy to understand:

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

void trimmer(char frase[]) {
    //Parametros iniciais
    int posPrimeiroChar=0;
    int posUltimoChar=strlen(frase)-1;
    int i;
    
    //Encontra primeiro caractere diferente de espaço
    while (frase[posPrimeiroChar] == ' ') posPrimeiroChar++;
    while (frase[posUltimoChar] == ' ') posUltimoChar--;
    
    //Rearranja string
    for (i = posPrimeiroChar; i <= posUltimoChar; i++) {
        frase[i-posPrimeiroChar] = frase[i];
    }

    //Finaliza a string
    frase[i-posPrimeiroChar] = '\0';
}

int main(){
 char frase[]="    Eu nao fui a escola!    ";
 printf("%s %lu\n",frase,strlen(frase));
 trimmer(frase);
 printf("%s %lu\n",frase,strlen(frase));
 return 0;
}

Can test in https://ideone.com/NAOnhc

Browser other questions tagged

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