Другие языки программирования и технологии

VS/C++ разбиение строки из 10 слов.

скажите как разбить строку, и занести одно конкретное слово в массив char. Виду что есть функция split но до сих пор не понимаю как правильно её описывать.
Это на с++.NET:
#using <mscorlib.dll>

using namespace System;
using namespace System::Collections;

int main()
{

String* delimStr = S" ,.:";
Char delimiter[] = delimStr->ToCharArray();
String* words = S"one two,three:four.";
String* split[] = 0;

Console::WriteLine(S"The delimiters are -{0}-", delimStr);
for (int x = 1; x <= 5; x++) {
split = words->Split(delimiter, x);
Console::WriteLine(S"\ncount = {0, 2} ...", __box(x));
IEnumerator* myEnum = split->GetEnumerator();
while (myEnum->MoveNext()) {
String* s = __try_cast<string*>(myEnum->Current);
Console::WriteLine(S"-{0}-", s);
}
}
}
Еркебулан Жубатыров
Еркебулан Жубатыров
35 996
Лучший ответ
> как разбить строку
Зачем что-то разбивать, если тебе нужно одно конкретное слово?

> занести одно конкретное слово в массив char
Зачем нужен char[], если можно пользоваться более удобным string?

#include <string>
#include <iostream>

std::string nth_word(std::string &s, int nw, std::string &d) {
    int c = 0, b, e = 0;
    do {
        b = s.find_first_not_of(d, e);
        e = s.find_first_of(d, b);
        ++c;
    } while (b != s.npos && c <= nw);
    return b != s.npos? s.substr(b, e - b) : "";
}

std::string nth_word(std::string &s, int nw) { return nth_word(s, nw, std::string(" ")); }

int main() {
    std::string s = "omfg you do not kill! clown clown kills you!";
    std::cout << "word #3: '" << nth_word(s, 3) << "'\n";
}

Если уж так нужно что-то там "разбить", то вместо массивов лучше использовать контейнеры из STL. Здесь все слова из строки помещаются в vector, который есть более удобная замена обычному массиву:

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

std::vector<std::string> split(std::string &str, std::string &del) {
    std::vector<std::string> result;
    int b = str.find_first_not_of(del), e;
    while (b != str.npos) {
        result.push_back(str.substr(b, (e = str.find_first_of(del, b)) - b));
        b = str.find_first_not_of(del, e);
    }
    return result;
}

int main() {
    std::string s = "omfg you do not kill! clown clown kills you!", d = " !";
    std::vector<std::string> words = split(s, d);
    for (int c = 0; c < words.size(); ++c) std::cout << words[c] << std::endl;
}
SA
Sahin Aliyev
90 966
Александр Чиняев А как find_first_of работает в Visual C++?