C++ 如何查找字符串中包含数字的单词
我需要检查字符串中的单词,看看它们是否包含数字,如果没有,请删除这个单词。然后打印出修改后的字符串 这是我为解决这个问题所做的努力,但它并没有像我需要的那样起作用C++ 如何查找字符串中包含数字的单词,c++,string,vector,C++,String,Vector,我需要检查字符串中的单词,看看它们是否包含数字,如果没有,请删除这个单词。然后打印出修改后的字符串 这是我为解决这个问题所做的努力,但它并没有像我需要的那样起作用 void sentence_without_latin_character( std::string &s ) { std::cout << std::endl; std::istringstream is (s); std::string word; std::vector<
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;
}
没有拉丁字符的无效句子(std::string&s){
std::cout>word){
std::string::size\u type temp\u size=word.find(std::ctype\u base::digit);
如果(临时大小==std::string::npos){
word.erase(word.begin()、word.begin()+临时大小);
}
单词和其他字符。推回(单词);
}
for(const auto i:带有其他字符的单词){
std::cout这部分没有做你认为它做的事情:
word.find(std::ctype_base::digit);
仅搜索完整的子字符串(或单个字符)
如果要搜索字符串中的一组字符,请改用
另一种选择是使用类似的方法测试每个字符,可能使用类似算法或简单循环。正如Acorn解释的那样,word.find(std::ctype\u base::digit)
不搜索第一个数字。std::ctype\u base::digit
是一个常量,指示特定std::ctype
方法的数字。实际上,有一个名为scan\u的
void sentence_without_latin_character( std::string &s ) {
std::istringstream is (s);
std::string word;
s.clear();
auto& ctype = std::use_facet<std::ctype<char>>(std::locale("en_US.utf8"));
while (is >> word) {
auto p = ctype.scan_is(std::ctype_base::digit, word.data(), &word.back()+1);
if (p == &word.back()+1) {
s += word;
if (is.peek() == ' ') s += ' ';
}
}
std::cout << s << std::endl;
}
没有拉丁字符的无效句子(std::string&s){
std::istringstream为(s);
字符串字;
s、 清除();
auto&ctype=std::use_facet(std::locale(“en_US.utf8”);
while(is>>word){
自动p=ctype.scan_是(std::ctype_base::digit,word.data(),&word.back()+1);
if(p==&word.back()+1){
s+=单词;
如果(is.peek()='')s+='';
}
}
你能用std::regex吗?