gpt4 book ai didi

C++迭代字符串中空格不规则的单词

转载 作者:行者123 更新时间:2023-11-30 01:34:18 27 4
gpt4 key购买 nike

假设我们有一个字符串,单词之间的空格不规则,如下所示:

roberto           1007   2.3  6.4  7127016 534260   ??  S    10:18AM   5:32.46 /Applications/Firefox.app/Contents/MacOS/firefox  

如何创建一个包含所有单词的数组?

这是我的基本解决方案:

std:: string = "roberto           1007   2.3  6.4  7127016 534260   ??  S    10:18AM   5:32.46 /Applications/Firefox.app/Contents/MacOS/firefox  ";   
size_t length = strlen(string.data());
std::vector<std::string> words;
std::string temp;
for (int i = 0; i < length; i++) {
if (string[i] != ' ') {
temp.push_back(string[i]);
} else {
if (!temp.empty()) {
words.push_back(temp);
temp = "";
}
}
}

std::cout << "words are: " << std::endl;
for (const auto &word : words) {
std::cout << word << std::endl;
}

感谢您的关注。

最佳答案

流操作删除前导空格。

#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <sstream>

template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec)
{
for (auto& el : vec)
{
os << el << std::endl;
}
return os;
}

int main()
{
std::string input = "roberto 1007 2.3 6.4 7127016 534260 ?? S 10:18AM 5:32.46 /Applications/Firefox.app/Contents/MacOS/firefox ";
std::istringstream iss(input);
std::vector<std::string> results(std::istream_iterator<std::string>{iss}, {});

std::cout << results << std::endl;
}

See it live

关于C++迭代字符串中空格不规则的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56662409/

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