如何解析含整数的字符串?以str="1Apple2Banana3Cat4Dog"为例求方案
解决字符串中提取数字后英文单词的问题
这个问题我之前也碰到过!核心问题出在stringstream默认的字符串读取逻辑上,咱们先搞清楚为什么你的代码没得到预期结果,再给出几种可行的解决办法。
为什么原代码失效?
你的代码里,ss>>i会成功读取开头的整数1,但接下来的ss>>s是按照空白字符来分割字符串的——而你的目标字符串"1Apple2Banana3Cat4Dog"里根本没有空格,所以ss>>s会直接把从当前位置(Apple开头)到字符串末尾的所有内容一次性读入s,自然就输出了Apple2Banana3Cat4Dog。
三种可行的解决办法
方法一:逐个字符遍历处理
手动遍历字符串,跳过数字字符,收集连续的字母字符作为一个单词,遇到数字就输出之前收集的内容(如果有的话):
#include <iostream> #include <string> #include <cctype> using namespace std; int main() { string str = "1Apple2Banana3Cat4Dog"; string current; for (char c : str) { if (isdigit(c)) { if (!current.empty()) { cout << current << endl; current.clear(); } } else { current += c; } } // 处理最后一个单词(循环结束后current里的内容) if (!current.empty()) { cout << current << endl; } return 0; }
这种方法逻辑直观,不需要依赖额外库,兼容性好。
方法二:使用正则表达式(C++11及以上)
利用正则表达式匹配所有非数字的连续字符序列,一次性提取所有目标单词:
#include <iostream> #include <string> #include <regex> #include <vector> using namespace std; int main() { string str = "1Apple2Banana3Cat4Dog"; regex reg("[^0-9]+"); // 匹配一个或多个非数字字符 sregex_iterator it(str.begin(), str.end(), reg); sregex_iterator end; for (; it != end; ++it) { cout << it->str() << endl; } return 0; }
这种代码更简洁,适合处理复杂的字符串匹配场景,不过需要编译器支持C++11及以上标准。
方法三:自定义stringstream的分隔符
把数字字符设置为stringstream的分隔符,这样就能按数字分割字符串了:
#include <iostream> #include <string> #include <sstream> #include <locale> using namespace std; // 自定义分隔符规则:数字作为分隔符 struct DigitSeparator : std::ctype<char> { DigitSeparator() : std::ctype<char>(get_table()) {} static const std::ctype_base::mask* get_table() { static std::vector<std::ctype_base::mask> table(std::ctype<char>::table_size, std::ctype_base::mask()); for (char c = '0'; c <= '9'; ++c) { table[c] = std::ctype_base::space; // 把数字标记为空白分隔符 } return table.data(); } }; int main() { string str = "1Apple2Banana3Cat4Dog"; stringstream ss(str); ss.imbue(locale(ss.getloc(), new DigitSeparator())); // 应用自定义分隔规则 string s; while (ss >> s) { // 现在会自动跳过数字,读取中间的单词 cout << s << endl; } return 0; }
这种方法利用了stringstream的本地化特性,适合想继续使用stringstream的场景,代码稍复杂但扩展性强。
以上三种方法都能得到你想要的输出:
Apple Banana Cat Dog
内容的提问来源于stack exchange,提问作者rajshekhar y dodamani
相关产品推荐
相关产品推荐

