Другие языки программирования и технологии
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);
}
}
}
#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);
}
}
}
> как разбить строку
Зачем что-то разбивать, если тебе нужно одно конкретное слово?
> занести одно конкретное слово в массив 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;
}
Зачем что-то разбивать, если тебе нужно одно конкретное слово?
> занести одно конкретное слово в массив 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;
}
Александр Чиняев
А как find_first_of работает в Visual C++?
Похожие вопросы
- C++ vs C# vs Java Что лучше для игростроя? Какой язык лучше изучать для разработки игр?
- У вас такие же ощущения от языков программирования ? (C++ vs C#)
- Нужно на с++ написать программу по заданию:даны две строки, содержащие не более 100 символов. Строки состоят из слов, р
- Как указать версию программы, название и автора в VS C++
- Дана строка, состоящая из слов, разделенных символами, которые перечислены во второй строке. Показать все слова На С++
- C++ VS C# дайте вашу субъективную оценку этим двум языкам, какие плюсы, какие минусы, и есть ли задачи с которыми может
- Помогите написать задачу по C++ Дана строка. найти в ней самое длинное слово-палиндром.
- Python vs C++ что учить?
- C передать строку 1 параметра в массив
- c++, массивы, строки