gpt4 book ai didi

c++ - 如何在字符串中查找包含数字的单词

转载 作者:搜寻专家 更新时间:2023-10-31 02:04:16 28 4
gpt4 key购买 nike

我需要检查字符串中的单词以查看其中是否包含数字,如果不是,则删除该单词。然后打印出修改后的字符串

这是我为解决问题所做的努力,但它并没有像我需要的那样工作

void sentence_without_latin_character( std::string &s ) {
std::cout << std::endl;

std::istringstream is (s);
std::string word;
std::vector<std::string> words_with_other_characters;

while (is >> word) {
std::string::size_type temp_size = word.find(std::ctype_base::digit);
if (temp_size == std::string::npos) {
word.erase(word.begin(), word.begin() + temp_size);
}
words_with_other_characters.push_back(word);
}

for (const auto i: words_with_other_characters) {
std::cout << i << " ";
}

std::cout << std::endl;
}

最佳答案

这部分并没有按照你的想法去做:

word.find(std::ctype_base::digit);

std::string::find仅搜索完整的子字符串(或单个字符)。

如果要搜索字符串中的一组字符,请使用 std::string::find_first_of相反。

另一种选择是使用类似 std::isdigit 的方式测试每个字符,可能使用类似 std::any_of 的算法或者用一个简单的循环。

关于c++ - 如何在字符串中查找包含数字的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53805864/

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