如何遍历字符串中的单词

如何遍历字符串中的单词

技术背景

在C++编程中,经常需要对字符串进行处理,例如将字符串按特定分隔符拆分成多个单词,并对这些单词进行遍历操作。然而,C++标准库并没有直接提供这样的方法,因此需要开发者自己实现或者借助第三方库来完成。

实现步骤

1. 使用std::istringstream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <string>
#include <sstream>
#include <vector>

template <typename Out>
void split(const std::string &s, char delim, Out result) {
std::istringstream iss(s);
std::string item;
while (std::getline(iss, item, delim)) {
*result++ = item;
}
}

std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
}

2. 使用std::copyistream_iterator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>

int main() {
std::string sentence = "And I feel fine...";
std::istringstream iss(sentence);
std::vector<std::string> tokens;
std::copy(std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>(),
std::back_inserter(tokens));
return 0;
}

3. 使用Boost库

1
2
3
4
5
6
7
8
9
#include <boost/algorithm/string.hpp>
#include <vector>
#include <string>

int main() {
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of("\t "));
return 0;
}

4. 使用模板函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <vector>
#include <string>
#include <utility>

template < typename StringT,
typename DelimiterT = char,
typename ContainerT = std::vector<std::string_view> >
ContainerT split(StringT const& str, DelimiterT const& delimiters = ' ', bool trimEmpty = true, ContainerT&& tokens = {})
{
typename StringT::size_type pos, lastPos = 0, length = str.length();

while (lastPos < length + 1)
{
pos = str.find_first_of(delimiters, lastPos);
if (pos == StringT::npos)
pos = length;

if (pos != lastPos || !trimEmpty)
tokens.emplace_back(str.data() + lastPos, pos - lastPos);

lastPos = pos + 1;
}

return std::forward<ContainerT>(tokens);
}

核心代码

以下是一个使用std::istringstream遍历字符串单词的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
#include <sstream>

int main() {
std::string line = "a line of text to iterate through";
std::string word;
std::istringstream iss(line, std::istringstream::in);
while (iss >> word) {
std::cout << word << std::endl;
}
return 0;
}

最佳实践

  • 性能考虑:如果对性能要求较高,建议使用std::string_view,它避免了不必要的字符串复制,提高了效率。
  • 代码复用:将字符串分割和遍历的逻辑封装成函数或模板,提高代码的复用性。
  • 错误处理:在处理字符串时,要考虑到各种边界情况,如空字符串、连续分隔符等,确保代码的健壮性。

常见问题

  • 空令牌处理:某些方法可能会保留空令牌,需要根据具体需求进行处理。
  • 多分隔符处理:如果需要按多个分隔符进行分割,可以使用find_first_of或正则表达式。
  • 内存管理:在使用动态分配内存的容器时,要注意内存的使用和释放,避免内存泄漏。

如何遍历字符串中的单词
https://119291.xyz/posts/2025-05-09.how-to-iterate-over-words-of-a-string/
作者
ww
发布于
2025年5月9日
许可协议