使用单个区别符分开字符串

Splitting a string using a single delimeter

本文关键字:字符串 区别 单个      更新时间:2023-10-16

可能的重复:
在C

中拆分字符串

我正在尝试将带有分配器的单个字符串对象分为单独的字符串,然后输出单个字符串。

例如,输入字符串是firstName,lastname-age-cuputation-telephone

' - '字符是特定器,我需要仅使用字符串类函数分别输出它们。

最好的方法是什么?我很难理解。substr和类似功能。

谢谢!

我认为字符串流和 getline可以易于阅读代码:

#include <string>
#include <sstream>
#include <iostream>
std::string s = "firstname,lastname-age-occupation-telephone";
std::istringstream iss(s);
for (std::string item; std::getline(iss, item, '-'); )
{
    std::cout << "Found token: " << item << std::endl;
}

这仅使用string成员函数:

for (std::string::size_type pos, cur = 0;
     (pos = s.find('-', cur)) != s.npos || cur != s.npos; cur = pos)
{
    std::cout << "Found token: " << s.substr(cur, pos - cur) << std::endl;
    if (pos != s.npos) ++pos;  // gobble up the delimiter
}

我会做这样的事情

do
{        
    std::string::size_type posEnd = myString.find(delim);
    //your first token is [0, posEnd). Do whatever you want with it.
    //e.g. if you want to get it as a string, use
    //myString.substr(0, posEnd - pos);
    myString = substr(posEnd);
}while(posEnd != std::string::npos);