简体   繁体   English

删除字符串数组中的空格并计算空格 C

[英]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";例如:- char array[]="I'm new to programing";

I want to rewrite code that variable remove spaces array[]="I'mnewtoprograming"我想重写变量删除空格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.您需要跟踪字符串中当前的 position 以及将下一个字符与空格进行比较的“尾部”。

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.array[]创建 For 循环并计算' '空格。 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.这条线是正确的,我看到一些评论说这条线是错误的。它与 if 条件相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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