gpt4 book ai didi

c++ - 使用 C 字符串和指针。删除除小写字母和空格之外的所有字符

转载 作者:行者123 更新时间:2023-11-30 01:38:14 25 4
gpt4 key购买 nike

我们被要求创建一个程序,从给定的字符串中删除除小写字母和空格之外的所有字符(使用指针)。

例子:

Enter a String: Hi there are #20 markers points to NORTH.

Output: i there are markers points to

这是我到目前为止得到的:

#include <iostream>
#include <cstring>
#include <cctype>

void lowerCase(char *text);

int main()
{
char str[100];
std::cout << "Enter a string: ";
std::cin.getline(str, 100);
lowerCase(str);
std::cout << "\nOutput after lowerCase():\n";
std::cout << str;

system("pause>0");
return 0;
}

void lowerCase(char *text)
{
while (*text != '\0') {
if (((unsigned int)*text >= 97 && (unsigned int)*text <= 122) || *text == ' ') {
text++;
}
else {
for (char *i = text; *i != '\0'; i++) {
*i = *(i + 1);
}
text++;
}
}
}

此代码的输出为:

Enter a String: Hi there are #20 markers points to NORTH.

Output after lowerCase():

i there are 2 markers points to OT.

如何实现示例中的结果?

最佳答案

你的函数 lowerCase()跳过应该删除的连续字符;如果您从逻辑上跟踪 else block ,您可以看到这一点:

else {
for (char *i = text; *i != '\0'; i++) {
*i = *(i + 1);
}
text++; // <- this always skips the next character
}

你不需要text++在 else block 中自 *i = *(i + 1)已经将下一个字符复制到 text 指向的位置.

关于c++ - 使用 C 字符串和指针。删除除小写字母和空格之外的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48391379/

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