gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:34:30 26 4
gpt4 key购买 nike

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

Read a string, print the string without space and the number of spaces.

我可以使用 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);

关于c - 删除/计算字符串中的空格(使用相同的字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16985524/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com