C++字符串分割: 超越istringstream的两种高效方法
C++字符串分割: 超越istringstream的两种高效方法
除了使用 std::istringstream 和 while 循环,还有其他方法可以实现按空白字符分割字符串。以下是两种更高效的选择:
**1. 使用 std::string 的 find_first_of 和 substr 函数:**cpp#include
int main() { std::string sentence = 'Hello, how are you today?'; std::string delimiters = ' '; // 空格、制表符、换行符
size_t start = 0, end = sentence.find_first_of(delimiters);
while (end != std::string::npos) { std::cout << sentence.substr(start, end - start) << std::endl; start = sentence.find_first_not_of(delimiters, end); end = sentence.find_first_of(delimiters, start); }
if (start != std::string::npos) { std::cout << sentence.substr(start) << std::endl; }
return 0;}
在这个示例中,我们使用 std::string 的 find_first_of 和 substr 函数,以及 start 和 end 两个指针来分割字符串。
- 首先,
find_first_of函数找到第一个空白字符的位置。- 然后,根据该位置使用substr函数提取子串。- 接下来,使用find_first_not_of和find_first_of函数找到下一个非空白字符的位置和下一个空白字符的位置,然后继续分割字符串,直到没有更多的空白字符。- 最后,检查是否还有剩余的非空白字符,并输出。
**2. 使用 C++11 中的正则表达式库 <regex>:**cpp#include
int main() { std::string sentence = 'Hello, how are you today?'; std::regex re('\s+'); // 匹配一个或多个空白字符
std::sregex_token_iterator it(sentence.begin(), sentence.end(), re, -1); std::sregex_token_iterator end;
while (it != end) { std::cout << *it++ << std::endl; }
return 0;}
在这个示例中,我们使用 <regex> 库中的正则表达式来实现分割。
- 首先,定义一个正则表达式
\s+,它匹配一个或多个空白字符。- 然后,使用std::sregex_token_iterator来迭代匹配到的子串,并输出每个子串。
总结:
这两种方法都可以实现按空白字符分割字符串的需求,你可以根据具体的情况选择适合的方法。
希望以上示例能够帮助你实现按空白字符分割字符串!如果你还有其他关于字符串分割、正则表达式或 C++ 的问题,请随时提问。
原文地址: https://www.cveoy.top/t/topic/cra2 著作权归作者所有。请勿转载和采集!