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

标签 c++ pointers c-strings

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

例子:

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/

相关文章:

java - 将 C 指针转换为 Java

C++ 指向指针的指针

c - 棘手的C函数测试知识静态、全局、局部变量和指针

c - 将 C 字符串的可变长度数组作为函数参数传递

c++ - 像关系数据库一样使用boost multi index

c++ - 从对话框窗口调用第二个对话框无法使任何一个处于事件状态

c++ - 将可变模板类的模板参数解包为常量和常量数组

C++ 无法将 lambda 转换为 std::pair 中的 std::packaged_task

将指针字符串复制到其他指针

c - 如何打印字符*