简体   繁体   中英

remove space in string array and count spaces C

I have a string line with an array. Ex:- char array[]="I'm new to programing";

I want to rewrite code that variable remove spaces array[]="I'mnewtoprograming"

I already tried to build this

  scanf("%[^\n]s",&line);

int len=strlen(line);
//remove space in lenth
   for(int i=0;i<len;i++)
       
       (line[i]==' ')?:newlen++;
       if (line[i]==' ')
       {
           line[i]=line[i+1];
       }

give me the reason that I mistake

You need to keep track of the current position in the string and the "tail" where next char is compared to the space.

char *removechar(char *str, int ch)
{
    char *cpos = str, *tail = str; 

    while(*tail)
    {
        if(*tail != ch)
        {
            *cpos++ = *tail++;
        }
        else
        {
            tail++;
        }
    }
    *cpos = 0;
    return str;
}

Make For loop for array[] and count ' ' spaces. line[i]=line[i+1]; this line is wrong.

(line[i]==' ')?:newlen++; this line is correct, i saw some comments that line was wrong.its same as if condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM