Answers:
您可以使用该std::string::find()
函数查找字符串定界符的位置,然后使用std::string::substr()
来获取标记。
例:
std::string s = "scott>=tiger";
std::string delimiter = ">=";
std::string token = s.substr(0, s.find(delimiter)); // token is "scott"
该find(const string& str, size_t pos = 0)
函数返回str
字符串中第一次出现的位置,或者返回npos
未找到字符串的位置。
该substr(size_t pos = 0, size_t n = npos)
函数返回对象的子字符串,从position pos
和length开始npos
。
如果您有多个定界符,则在提取了一个标记之后,可以将其删除(包括定界符)以进行后续提取(如果要保留原始字符串,只需使用s = s.substr(pos + delimiter.length());
):
s.erase(0, s.find(delimiter) + delimiter.length());
这样,您可以轻松地循环获取每个令牌。
std::string s = "scott>=tiger>=mushroom";
std::string delimiter = ">=";
size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
std::cout << token << std::endl;
s.erase(0, pos + delimiter.length());
}
std::cout << s << std::endl;
输出:
scott
tiger
mushroom
mushroom
循环外的输出,即s = mushroom
std::string token = s.substr(s.find(delimiter) + 1);
,如果您确定它存在(我使用+1的长度)...
此方法std::string::find
通过记住前一个子字符串标记的开始和结尾来使用而不会更改原始字符串。
#include <iostream>
#include <string>
int main()
{
std::string s = "scott>=tiger";
std::string delim = ">=";
auto start = 0U;
auto end = s.find(delim);
while (end != std::string::npos)
{
std::cout << s.substr(start, end - start) << std::endl;
start = end + delim.length();
end = s.find(delim, start);
}
std::cout << s.substr(start, end);
}
您可以使用next函数分割字符串:
vector<string> split(const string& str, const string& delim)
{
vector<string> tokens;
size_t prev = 0, pos = 0;
do
{
pos = str.find(delim, prev);
if (pos == string::npos) pos = str.length();
string token = str.substr(prev, pos-prev);
if (!token.empty()) tokens.push_back(token);
prev = pos + delim.length();
}
while (pos < str.length() && prev < str.length());
return tokens;
}
split("abc","a")
将返回一个向量或单个字符串"bc"
,在这里我认为如果它返回一个元素的向量将更有意义["", "bc"]
。str.split()
在Python中使用它对我来说很直观,以防万一delim
,无论是在开头还是结尾都应返回一个空字符串,但这只是我的看法。无论如何,我只是认为应该提及
if (!token.empty())
@kyriakosSt提到的prevent问题以及与连续定界符有关的其他问题。
if (!token.empty())
似乎不足以修复它。
根据字符串定界符分割字符串。例如"adsf-+qwret-+nvfkbdsj-+orthdfjgh-+dfjrleih"
基于字符串定界符分割字符串"-+"
,输出将是{"adsf", "qwret", "nvfkbdsj", "orthdfjgh", "dfjrleih"}
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
// for string delimiter
vector<string> split (string s, string delimiter) {
size_t pos_start = 0, pos_end, delim_len = delimiter.length();
string token;
vector<string> res;
while ((pos_end = s.find (delimiter, pos_start)) != string::npos) {
token = s.substr (pos_start, pos_end - pos_start);
pos_start = pos_end + delim_len;
res.push_back (token);
}
res.push_back (s.substr (pos_start));
return res;
}
int main() {
string str = "adsf-+qwret-+nvfkbdsj-+orthdfjgh-+dfjrleih";
string delimiter = "-+";
vector<string> v = split (str, delimiter);
for (auto i : v) cout << i << endl;
return 0;
}
输出量
广告 qwret nvfkbdsj Orthdfjgh dfjrleih
根据字符定界符分割字符串。如"adsf+qwer+poui+fdgh"
用定界符分割字符串"+"
将输出{"adsf", "qwer", "poui", "fdg"h}
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
vector<string> split (const string &s, char delim) {
vector<string> result;
stringstream ss (s);
string item;
while (getline (ss, item, delim)) {
result.push_back (item);
}
return result;
}
int main() {
string str = "adsf+qwer+poui+fdgh";
vector<string> v = split (str, '+');
for (auto i : v) cout << i << endl;
return 0;
}
输出量
广告 wer ui d
vector<string>
我认为它将调用复制构造函数。
此代码从文本中拆分行,然后将所有人添加到向量中。
vector<string> split(char *phrase, string delimiter){
vector<string> list;
string s = string(phrase);
size_t pos = 0;
string token;
while ((pos = s.find(delimiter)) != string::npos) {
token = s.substr(0, pos);
list.push_back(token);
s.erase(0, pos + delimiter.length());
}
list.push_back(s);
return list;
}
致电者:
vector<string> listFilesMax = split(buffer, "\n");
vector<string> split(char *phrase, const string delimiter="\n")
strtok允许您传入多个字符作为分隔符。我敢打赌,如果您传入“> =”,您的示例字符串将被正确分割(即使>和=被视为单独的分隔符)。
如果不想使用c_str()
从字符串转换为char *进行编辑,则可以使用substr和find_first_of进行标记化。
string token, mystring("scott>=tiger");
while(token != mystring){
token = mystring.substr(0,mystring.find_first_of(">="));
mystring = mystring.substr(mystring.find_first_of(">=") + 1);
printf("%s ",token.c_str());
}
strtok()
,因为它将要求我使用char数组而不是字符串。
.c_str()
便宜又容易。
这是我的看法。它处理边缘情况,并采用可选参数从结果中删除空条目。
bool endsWith(const std::string& s, const std::string& suffix)
{
return s.size() >= suffix.size() &&
s.substr(s.size() - suffix.size()) == suffix;
}
std::vector<std::string> split(const std::string& s, const std::string& delimiter, const bool& removeEmptyEntries = false)
{
std::vector<std::string> tokens;
for (size_t start = 0, end; start < s.length(); start = end + delimiter.length())
{
size_t position = s.find(delimiter, start);
end = position != string::npos ? position : s.length();
std::string token = s.substr(start, end - start);
if (!removeEmptyEntries || !token.empty())
{
tokens.push_back(token);
}
}
if (!removeEmptyEntries &&
(s.empty() || endsWith(s, delimiter)))
{
tokens.push_back("");
}
return tokens;
}
例子
split("a-b-c", "-"); // [3]("a","b","c")
split("a--c", "-"); // [3]("a","","c")
split("-b-", "-"); // [3]("","b","")
split("--c--", "-"); // [5]("","","c","","")
split("--c--", "-", true); // [1]("c")
split("a", "-"); // [1]("a")
split("", "-"); // [1]("")
split("", "-", true); // [0]()
这对于字符串(或单个字符)定界符应该是完美的。别忘了包含#include <sstream>
。
std::string input = "Alfa=,+Bravo=,+Charlie=,+Delta";
std::string delimiter = "=,+";
std::istringstream ss(input);
std::string token;
std::string::iterator it;
while(std::getline(ss, token, *(it = delimiter.begin()))) {
while(*(++it)) ss.get();
std::cout << token << " " << '\n';
}
第一个while循环使用字符串定界符的第一个字符提取令牌。第二个while循环跳过其余定界符,并在下一个标记的开头停止。
我会用boost::tokenizer
。以下文档说明了如何制作适当的令牌生成器功能:http : //www.boost.org/doc/libs/1_52_0/libs/tokenizer/tokenizerfunction.htm
这是适合您的情况的一种。
struct my_tokenizer_func
{
template<typename It>
bool operator()(It& next, It end, std::string & tok)
{
if (next == end)
return false;
char const * del = ">=";
auto pos = std::search(next, end, del, del + 2);
tok.assign(next, pos);
next = pos;
if (next != end)
std::advance(next, 2);
return true;
}
void reset() {}
};
int main()
{
std::string to_be_parsed = "1) one>=2) two>=3) three>=4) four";
for (auto i : boost::tokenizer<my_tokenizer_func>(to_be_parsed))
std::cout << i << '\n';
}
答案已经存在,但是selected-answer使用擦除功能,这非常昂贵,请考虑一些很大的字符串(以MB为单位)。因此,我使用以下功能。
vector<string> split(const string& i_str, const string& i_delim)
{
vector<string> result;
size_t found = i_str.find(i_delim);
size_t startIndex = 0;
while(found != string::npos)
{
string temp(i_str.begin()+startIndex, i_str.begin()+found);
result.push_back(temp);
startIndex = found + i_delim.size();
found = i_str.find(i_delim, startIndex);
}
if(startIndex != i_str.size())
result.push_back(string(i_str.begin()+startIndex, i_str.end()));
return result;
}
string.split()
方法。)
这是一个完整的方法,它可以在任何定界符上分割字符串并返回切碎的字符串的向量。
它是根据ryanbwork的答案改编而成。但是,他的检查:if(token != mystring)
如果字符串中有重复的元素,则会给出错误的结果。这是我解决该问题的方法。
vector<string> Split(string mystring, string delimiter)
{
vector<string> subStringList;
string token;
while (true)
{
size_t findfirst = mystring.find_first_of(delimiter);
if (findfirst == string::npos) //find_first_of returns npos if it couldn't find the delimiter anymore
{
subStringList.push_back(mystring); //push back the final piece of mystring
return subStringList;
}
token = mystring.substr(0, mystring.find_first_of(delimiter));
mystring = mystring.substr(mystring.find_first_of(delimiter) + 1);
subStringList.push_back(token);
}
return subStringList;
}
while (true)
在这样的一段代码中通常很难看到类似的东西。我个人建议你重写这一点,以便比较std::string::npos
(或分别针对检查mystring.size()
),使while (true)
过时。
如果您不想修改字符串(如Vincenzo Pii的回答),并且还希望输出最后一个标记,则可以使用以下方法:
inline std::vector<std::string> splitString( const std::string &s, const std::string &delimiter ){
std::vector<std::string> ret;
size_t start = 0;
size_t end = 0;
size_t len = 0;
std::string token;
do{ end = s.find(delimiter,start);
len = end - start;
token = s.substr(start, len);
ret.emplace_back( token );
start += len + delimiter.length();
std::cout << token << std::endl;
}while ( end != std::string::npos );
return ret;
}
#include<iostream>
#include<algorithm>
using namespace std;
int split_count(string str,char delimit){
return count(str.begin(),str.end(),delimit);
}
void split(string str,char delimit,string res[]){
int a=0,i=0;
while(a<str.size()){
res[i]=str.substr(a,str.find(delimit));
a+=res[i].size()+1;
i++;
}
}
int main(){
string a="abc.xyz.mno.def";
int x=split_count(a,'.')+1;
string res[x];
split(a,'.',res);
for(int i=0;i<x;i++)
cout<<res[i]<<endl;
return 0;
}
PS:仅在分割后的字符串长度相等时有效
功能:
std::vector<std::string> WSJCppCore::split(const std::string& sWhat, const std::string& sDelim) {
std::vector<std::string> vRet;
int nPos = 0;
int nLen = sWhat.length();
int nDelimLen = sDelim.length();
while (nPos < nLen) {
std::size_t nFoundPos = sWhat.find(sDelim, nPos);
if (nFoundPos != std::string::npos) {
std::string sToken = sWhat.substr(nPos, nFoundPos - nPos);
vRet.push_back(sToken);
nPos = nFoundPos + nDelimLen;
if (nFoundPos + nDelimLen == nLen) { // last delimiter
vRet.push_back("");
}
} else {
std::string sToken = sWhat.substr(nPos, nLen - nPos);
vRet.push_back(sToken);
break;
}
}
return vRet;
}
单元测试:
bool UnitTestSplit::run() {
bool bTestSuccess = true;
struct LTest {
LTest(
const std::string &sStr,
const std::string &sDelim,
const std::vector<std::string> &vExpectedVector
) {
this->sStr = sStr;
this->sDelim = sDelim;
this->vExpectedVector = vExpectedVector;
};
std::string sStr;
std::string sDelim;
std::vector<std::string> vExpectedVector;
};
std::vector<LTest> tests;
tests.push_back(LTest("1 2 3 4 5", " ", {"1", "2", "3", "4", "5"}));
tests.push_back(LTest("|1f|2п|3%^|44354|5kdasjfdre|2", "|", {"", "1f", "2п", "3%^", "44354", "5kdasjfdre", "2"}));
tests.push_back(LTest("|1f|2п|3%^|44354|5kdasjfdre|", "|", {"", "1f", "2п", "3%^", "44354", "5kdasjfdre", ""}));
tests.push_back(LTest("some1 => some2 => some3", "=>", {"some1 ", " some2 ", " some3"}));
tests.push_back(LTest("some1 => some2 => some3 =>", "=>", {"some1 ", " some2 ", " some3 ", ""}));
for (int i = 0; i < tests.size(); i++) {
LTest test = tests[i];
std::string sPrefix = "test" + std::to_string(i) + "(\"" + test.sStr + "\")";
std::vector<std::string> vSplitted = WSJCppCore::split(test.sStr, test.sDelim);
compareN(bTestSuccess, sPrefix + ": size", vSplitted.size(), test.vExpectedVector.size());
int nMin = std::min(vSplitted.size(), test.vExpectedVector.size());
for (int n = 0; n < nMin; n++) {
compareS(bTestSuccess, sPrefix + ", element: " + std::to_string(n), vSplitted[n], test.vExpectedVector[n]);
}
}
return bTestSuccess;
}
std::vector<std::string> parse(std::string str,std::string delim){
std::vector<std::string> tokens;
char *str_c = strdup(str.c_str());
char* token = NULL;
token = strtok(str_c, delim.c_str());
while (token != NULL) {
tokens.push_back(std::string(token));
token = strtok(NULL, delim.c_str());
}
delete[] str_c;
return tokens;
}
std::vector<std::string> split(const std::string& s, char c) {
std::vector<std::string> v;
unsigned int ii = 0;
unsigned int j = s.find(c);
while (j < s.length()) {
v.push_back(s.substr(i, j - i));
i = ++j;
j = s.find(c, j);
if (j >= s.length()) {
v.push_back(s.substr(i, s,length()));
break;
}
}
return v;
}
size_t last = 0; size_t next = 0; while ((next = s.find(delimiter, last)) != string::npos) { cout << s.substr(last, next-last) << endl; last = next + 1; } cout << s.substr(last) << endl;