在下面的程序中,我需要插入字符串直到'|'集合中的字符。
但是在删除字符'|'之后在我的代码中,我无法跳过所有字符直到最后。
输入:+919845012345, 0987654321, 987654320|9845012345, +91987654321, 0987654320, 987654323, 987654320
预期输出:+919845012345、0987654321、987654320
注意:(1)输入数据后,输入exit。 (2) substring 函数不能用于此目的。
#include<iostream>
#include <unordered_set>
#include<string>
using namespace std;
int main()
{
string str;
string::iterator it;
unordered_set <string> s;
while(getline(cin,str)) //
{
if(str=="exit")
{
break;
}
for (it= str.begin(); it !=str.end(); it++)
{
if (*it =='|')
{
it = str.erase(it);
}
}
s.insert(str);
}
for ( unordered_set<string> ::const_iterator itr = s.begin(); itr != s.end(); ++itr) {
cout<<*itr<<endl;
}
return 1;
}
最佳答案
尝试使用 string::find_first_of 看这里: * http://www.cplusplus.com/reference/string/string/find_first_of/ *
使用上面的函数找到下一个分隔符“|”的索引并从范围(子字符串)中创建一个字符串。 与替代方法相比,这种方法也非常快。 另一种选择是对字符串的拷贝使用 C 的 strtok。
关于c++ - 如何在出现特定字符后跳过字符串中的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20056701/