gpt4 book ai didi

c++ - 删除/忽略 Cstring 中除字符以外的所有内容

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

我正在尝试阅读一些长度不超过 100 个字符的文本,然后去掉其中的空格、数字、特殊字符等。我正在考虑如何进行此操作,但我想我一定忘记了我所知道的关于 cstrings 等的大部分内容。我最初只是想接受基本字符并将它们复制到一个新字符串中,但是 1。我不知道如何编写它,所以我的编译器不讨厌我和 2。我很确定我不希望新的、剥离的字符串中有空格(我很确定我的代码到目前为止会导致这种情况发生,如果它能工作的话)。

char * userText="";
char * justCharTxt;

cout << "Enter text: " << endl;
cin.getline(userText, STRING_SIZE);
for (int i = 0; i < strlen(userText); i++){
if (((userText[i] >= 'a') && (userText[i] <= 'z')) ||
((userText[i] >= 'A') && (userText[i] <= 'Z')))
*justCharTxt = userTxt[i];
}

关于这个问题的一些指导会很棒。谢谢!

最佳答案

只需使用 std::string,无需摆弄 char 数组或指针。

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
std::string line;
getline(std::cin, line);

line.erase(
std::remove_if(line.begin(), line.end(),
[](char c) {return !isalpha(c, std::locale());}),
line.end()
);

std::cout << line << '\n';
}

关于c++ - 删除/忽略 Cstring 中除字符以外的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23257947/

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