编辑1
cin
我有一个字符串,例如“嗨;我的;;名字是Andrea;我喜欢C ++”。我想创建一个用该字符串初始化的stringstream,并在last之前获取所有内容;
。
这是我尝试过的:
string ex("Hi; my;; name is Andrea;; and I like C++"), text, final_text;
stringstream loop_stream(ex);
int findComma = loop_stream.str().find(';');
do {
getline(loop_stream, text, ';');
loop_stream.ignore(1);
final_text += text;
loop_stream << loop_stream.rdbuf();
findComma = loop_stream.str().find(';');
while (findComma == 1) {
loop_stream.ignore(1);
}
findComma = loop_stream.str().find(';');
}
while (findComma != string::npos);
cout << "-" << final_text << "-" << endl;
但它根本不起作用...我希望输出为:
-Hi; my;; name is Andrea-
这是使用的另一种解决方案find_last_of
:
#include <string>
#include <iostream>
int main()
{
std:: string test = "Hi; my;; name is Andrea; and I like C++";
auto pos = test.find_last_of(";");
if ( pos != std::string::npos)
std::cout << test.substr(0, pos);
}
输出:
Hi; my;; name is Andrea
使用功能:
#include <string>
#include <iostream>
std::string parseString(const std::string& s)
{
auto pos = s.find_last_of(";");
if ( pos != std::string::npos)
return s.substr(0, pos);
return s;
}
int main()
{
std::cin >> test; // assume the string will be inputed
std::cout << parseString(test);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句