gpt4 book ai didi

c++ - 提取所有由非字母字符分隔的单词

转载 作者:行者123 更新时间:2023-12-02 09:57:45 25 4
gpt4 key购买 nike

给定一个字符串,例如:

std::string word = "Hello World!it's@.-/sunday";
我想提取所有以非字母字母分隔的单词,这些单词存储在像 vector 这样的容器中,因此对于这种情况,它将是:
Hello, World, it, s, sunday 
我最初的尝试是使用isalpha()以及相应的对substr()的索引计数,如下所示:
std::string word = "Hello World!it's@.-/sunday";
int count = 0, index = 0;
std::string temp;

for (; count < word.length();count++){
if (!isalpha(word[count])){
temp = word.substr(index,count);
index = count;
}
}
但这无法正常工作,因为我认为索引更新得不够快,导致单词混入非字母字符。也许有功能或更好的方法来提取所说的单词?

最佳答案

您可以尝试以下代码。它按字符构造单词char。

#include <string>
#include <iostream>
#include <vector>

int main()
{
std::string phrase = "Hello World!it's@.-/sunday";
std::vector<std::string> words;
std::string tmp;
for (const char &c:phrase)
{
if (isalpha(c))
{
tmp.push_back(c);
}
else
{
words.push_back(tmp);
tmp = "";
}
}
if (!tmp.empty())
{
words.push_back(tmp);
}

for (const auto w : words)
{
std::cout << w << std::endl;
}

return 0;
}

关于c++ - 提取所有由非字母字符分隔的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64380888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com