Untitled
unknown
plain_text
3 years ago
1.4 kB
12
Indexable
struct Word {
int length;
char *word;
Word() : word(0), length(0) {}
~Word() {
if (word) {
delete word;
}
}
void set(const char *startPos, int size) {
word = new char[size + 1];
memcpy(word, startPos, size);
word[size] = '\0';
length = size;
}
};
const char *input = " * * * * HHHH ZZZZ";
// Вычисляем кол-во слов.
int words = 0;
int length = strlen(input);
for (int i = 0; i < length; ++i) {
if (input[i] != ' ' && (i == 0 || input[i - 1] == ' ')) { // учитываем так же ситуации когда пробелов может быть несколько
++words;
}
}
if (words == 0) {
return 0;
}
Word *res = new Word[words];
int itRes = 0;
const char *startPos = input;
const char *spacePos = strchr(startPos, ' ');
while (spacePos != 0) {
int size = spacePos - startPos;
if (size > 0) {
res[itRes++].set(startPos, size);
}
startPos = spacePos + 1;
spacePos = strchr(startPos, ' ');
}
// Ситуация когда последнее слова не заканчивается пробелом
if (itRes < words) {
int size = length - (startPos - input);
res[itRes++].set(startPos, size);
}
delete[] res; // чистим результат, в реальной проге куда-то его используешьEditor is loading...