C ++中的字符串流来解析单词字符串&数字 [英] String Stream in C++ to parse string of words & numbers
问题描述
我有这样的字符串:'123plus43times7'
I have string like this: '123plus43times7'
数字后面是字典中的单词.
where numbers are followed by words from a dictionary.
我知道我可以使用 >>
操作符提取整数/数字:
I understand that I can extract int/numbers by using the >>
operator:
StringStream >> number
我可以得到号码.但是,Stream 中仍然包含编号.当数字的长度未知时如何删除数字,或者我应该找出数字的长度然后使用 str.substr() 创建一个新的 String Stream ?任何其他使用 C++ STL String 和 SStream 执行此操作的更好方法将不胜感激.
I can get the number. However, the Stream still has the number in it. How do I remove the number when the length of number is unknown or should I find out length of number and then use str.substr() to create a new String Stream ? Any other better method for doing it using C++ STL String and SStream would be really appreciated.
推荐答案
可以在文本和数字之间插入空格,然后使用std::stringstream
You can insert blank space between text and numbers and then use std::stringstream
#include <iostream>
#include <string>
#include <sstream>
#include <cctype>
int main()
{
std::string s = "123plus43times7";
for (size_t i = 0; i < (s.size() -1 ); i++)
{
if (std::isalpha(s[i]) != std::isalpha(s[i + 1]))
{
i++;
s.insert(i, " ");
}
}
std::stringstream ss(s);
while (ss >> s)
std::cout << s << "\n";
return 0;
}
这篇关于C ++中的字符串流来解析单词字符串&数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!