c++ - 如何在出现特定字符后跳过字符串中的所有字符

标签 c++ string set

在下面的程序中,我需要插入字符串直到'|'集合中的字符。

但是在删除字符'|'之后在我的代码中,我无法跳过所有字符直到最后。

输入:+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/

相关文章:

c++ - 将 bpftrace 探针附加到 C++ 函数

c++ - 打开文件时出现问题并且可能将文件输入/输出到字符串

javascript - 帮助转换内联 onclick

javascript - 继承自 Set.prototype

c++ - 显示不在 3D 中的不移动文本(例如显示 HUD 或帧速率)

c++ - C++-代码优化

php - 在 PHP 扩展中使用 PHP 函数

java - 在字符串的特殊字符前添加 escape "\"

java - + 字符串类中的运算符

swift - 一组可散列的自定义元素插入相等的元素