str = "abc@163.com;def@163.com;ghi@163.com;",每次迴圈提取一段,遇到分號停止。
string str = "abc@163.com;def@163.com;ghi@163.com;";
size_t begin = 0, end = 0;
while ((end = str.find(';', begin)) != string::npos) {
string token = str.substr(begin, end - begin);
cout << token << endl; // 處理 token
begin = end + 1;
}
// 處理最後一段(若無結尾分號)
if (begin < str.length()) {
cout << str.substr(begin) << endl;
}
// 手寫 split 返回 vector 零拷貝
vector split(string_view s, char delim) {
vector res;
size_t pos = 0;
while (pos < s.size()) {
size_t next = s.find(delim, pos);
res.emplace_back(s.substr(pos, next - pos));
if (next == string_view::npos) break;
pos = next + 1;
}
return res;
}
#include <boost/algorithm/string.hpp>
vector tokens;
boost::split(tokens, str, boost::is_any_of(";"), boost::token_compress_off);
find 返回 npos 表示未找到,迴圈終止條件。substr(pos, len) 不修改原字串,安全高效。token_compress_off 保留空串)。