如何在多个不同字符之间获取多个字符串

How can i get multiple string in between multiple different characters?

本文关键字:之间 获取 字符串 字符      更新时间:2023-10-16

我已经搜索了你的几个主题,但我似乎无法弄清楚如何在多个不同的字符之间切换。

string str = "AG/B/C,BC/D,AD,AE/R/B/A,AB";

我想在两个/或两个之间提取,只有
最终结果应该是:

B,AD,R,B,AB
string temp;
for(int i=0; i < str.size(); i++)     
    {
        temp += str[i];                  
        if((str[i] == '/') || str[i] == ',')                   
        {
            //do something
        }
    }
string temp = "";
char flag = ' ';
int cursor = 0;
for(int i = 0; i < str.size(); i++)
{
        if(str[i] == '/' || str[i] == ',')
        {
                if(flag == str[i] && cursor < i-1)
                        temp+=str.substr(cursor+1,i-cursor-1)+",";
                flag = str[i];
                cursor = i;
        }
}

这是一个复杂的用例,因为您希望分隔符成对执行。当然可以使用正则表达式来实现这一点,但恕我直言,读取写入都不会比直接处理更简单。只需存储最后一个分隔符。

string str = "AG/B/C,BC/D,AD,AE/R/B/A";
char last = '';   // initialize last separator to an impossible value
string temp;
for(size_t i=0; i < str.size(); i++)     
{
    if((str[i] == '/') || str[i] == ',')  // found a separator                 
    {
        if (last == str[i]) {     // is it the second on a pair
            std::cout << temp << std::endl; // or store temp in a vector for later use...
        }
        last = str[i];     // store last separator for future use
        temp.clear();      // reset the temp string
    }
    else temp.push_back(str[i]);  // non separator chars are added to temp string
}