繁体   English   中英

删除/计算字符串中的空格(使用相同的字符串)

[英]Remove/Count spaces in a string (using the same string)

我有一个简单的问题要解决:

读取一个字符串,打印没有空格的字符串和空格数。

我可以使用2个字符串执行此操作,一个用于存储用户字符串,另一个用于存储相同的字符串而不包含空格。 但我想只使用一个字符串。

到目前为止我所拥有的:

while(str[i] != '\0'){
        if(str[i] == ' '){
            contEsp += 1;
        }else{
            strcpy(&str[i - contEsp], &str[i]);
        }
        i++;
    }

问题:

它不计算空格数。

如果用户键入双倍或更多空间,则程序不会计数,也不会删除空格。

问题:

我的代码有问题吗?

是否可以只使用一个字符串来完成此操作?

试试这段代码:

int i = 0, contEsp =0;

while(str[i] != '\0')
{
    str[i-contEsp] = str[i];  

    if(str[i] == ' ')
      contEsp++;
    i++;       
}

str[i-contEsp] = '\0';

printf("String: %s, Spaces = %d\n",str, contEsp);

1)最后的空间也不要削减。 循环后添加检查和操作。

2)我建议划分当地空间计数器和全球空间计数器的概念。

unsigned int contEsp = 0;
unsigned int i = 0;
unsigned int localEsp = 0;

while(str[i] != '\0'){
    if(str[i] == ' '){
        contEsp += 1;
        localEsp += 1;
    }else if(contEsp) {
        strcpy(&str[i - localEsp], &str[i]);
        localEsp = 0;
        continue;
    }
    i++;
}

if ( localEsp > 0 )
    strcpy(&str[i - contEsp], &str[i]);

由于问题标记为“性能”:您的方法是在遇到空间时复制整个剩余字符串。 虽然实际上可能无关紧要,但效率低下。 只需逐个处理字符,例如:

unsigned remove_count_spaces(char *a) {
    char *b = a;
    unsigned ct = 0;

    do {
        if (*a == ' ') ct++;
        else *b++ = *a;
    } while(*a++);

    return ct;
}

...加上检查ct可能的环绕。

char* RemoveAndCountSpaces(char* s)
{
    int contEsp = 0;
    char* x = s;
    char* org = s;

    while(*s != '\0'){
        if(*s == ' '){
            contEsp++;
        } else {
            *x = *s;
            x++;
        }
        s++;
    }
    *x = *s;

    printf("%s\nSpaces Found: %d\n", org, contEsp);
    return org;
}

我的代码有问题吗?
1.计数未初始化为0
2. strcpy(&str[i - contEsp], &str[i]); 正在移动尚待处理的字符串,然后你的i不会为你想到的字符编制索引。

只使用一个字符串就可以做到这一点?
是的 - 下面

int CountAndBlank(char *str) {
  size_t x = 0;   /* index through un-spaced string */
  size_t i;       /* Index through original string */
  for (i = 0; str[i]; i++) {
    if (!str[i] == ' ') {
      str[x++] = str[i];
    }
  }
  str[x] = '\0';
  return i - x;  /* Spaces removed is the difference */
}

...
int Count = CountAndBlank(buf);
printf("Number of spaces removed from '%s' is %d\n", buf, Count);

暂无
暂无

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

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