C ++. Итерация слов в строке, где пробелы не являются регулярными - PullRequest
1 голос
/ 19 июня 2019

Предположим, у нас есть строка, где пробелы между словами не являются регулярными , например:

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;
}

Спасибо за внимание.

Ответы [ 3 ]

2 голосов
/ 19 июня 2019

Потоковые операции удаляют начальные пробелы.

#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;
}

Смотрите вживую

1 голос
/ 19 июня 2019

Непосредственно разделенная строка с пробелом. В списке будут пустые строки. Удалите их, используя стирание / удаление.

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

std::vector<std::string> splitString(std::string input, const char splitter ) {
        std::istringstream ss(input);
        std::string token;
        std::vector<std::string> values;
        while(std::getline(ss, token, splitter)) {
            values.push_back(token);
        }
        return values;
}

int main() {
    std::string str = "roberto           1007   2.3  6.4  7127016 534260   ??  S    10:18AM   5:32.46 /Applications/Firefox.app/Contents/MacOS/firefox";

    std::vector<std::string> res = splitString(str, ' ');

    res.erase(std::remove_if(res.begin(), res.end(), [](std::string& s){ return s.length() == 0; }), res.end());

    printf("%d", res.size());

    return 0;
}
1 голос
/ 19 июня 2019

1-й пробел можно удалить, а затем разделить на пробел

пример:

std::string input = "roberto           1007   2.3  6.4  7127016 534260   ??  S    10:18AM   5:32.46 /Applications/Firefox.app/Contents/MacOS/firefox  ";
auto lambdaPredicate = [](char lhs, char rhs)
{
    return (lhs == rhs) && (lhs == ' ');
};
// remove multiple spaces
std::string::iterator new_end = std::unique(input.begin(), input.end(), lambdaPredicate);
input.erase(new_end, input.end());
//split the string to a vector using space as delimitor
std::istringstream iss(input);
std::vector<std::string> results(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>());
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...