C++字符串分割: 超越istringstream的两种高效方法

除了使用 std::istringstreamwhile 循环,还有其他方法可以实现按空白字符分割字符串。以下是两种更高效的选择:

**1. 使用 std::stringfind_first_ofsubstr 函数:**cpp#include #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::stringfind_first_ofsubstr 函数,以及 startend 两个指针来分割字符串。

  • 首先,find_first_of 函数找到第一个空白字符的位置。- 然后,根据该位置使用 substr 函数提取子串。- 接下来,使用 find_first_not_offind_first_of 函数找到下一个非空白字符的位置和下一个空白字符的位置,然后继续分割字符串,直到没有更多的空白字符。- 最后,检查是否还有剩余的非空白字符,并输出。

**2. 使用 C++11 中的正则表达式库 <regex>:**cpp#include #include #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++ 的问题,请随时提问。

C++字符串分割: 超越istringstream的两种高效方法

原文地址: https://www.cveoy.top/t/topic/cra2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录