Hello! Help, please, with one task on Si. I enter the sentence from the keyboard. It is necessary to derive each word separately, but starting from the end of the sentence. that is, back to front. How to implement it?

    2 answers 2

    my code is a little bit more, but verified with comments: b

    #include <stdio.h> #include <string.h> using namespace std; int Count = 0; //количество слов int Begin[1111]; //wordsBegin[i] - индекс начала слова i в s int End[1111]; //wordsEnd[i] - индекс конца слова i в s char s[11111]; //предложение int sc = 0; //количество символов bool isSeparator(char c)//проверяет: служет ли символ разделителем слов. { if (c == ' ' || c == ',' || c == '.') return true; return false; } void addWord(int &last, int cur) //добавляет слово с номерами символов от last до cur { Begin[Count] = last; End[Count] = cur; last = cur + 2; Count++; } int main() { char c = getchar(); while (c != 10) { s[sc++] = c; c = getchar(); } int last = 0; //начало первого слова for (int i = 0; i < sc; i++)//разбираем наше предложение по словам { if (isSeparator(s[last])) last = i; //пропускаем разделители if (i > 0 && isSeparator(s[i]) && !isSeparator(s[i-1])) addWord(last, i-1); } addWord(last, sc-1); // возможно у нас осталось ещё слово, стоящее в конце предложения for (int i = Count-1; i >= 0; i--) //вывод слов в обратном порядке { for (int j = Begin[i]; j <= End[i]; j++) printf("%c", s[j]); printf(" "); //разделяем слова пробелом } return 0; } 
       char * s; // введенное предложение int length = getlen(s); for (int i = length - 1; i >= 0; i--) { if (s[i] == ' ' || i == 0) { printf(s + i + 1); s[i] = '\0'; } } 

      I did not chase away the absence of typos, so this can be considered a pseudocode. And nevertheless, I would like to ask if the author tried to solve this problem himself or immediately wrote to the portal, if he tried, then what was the actual difficulty. The question is professional (teaching) character :)

      • one
        And I would read the words using scanf (), then make a copy on the heap via strdup (), and put the addresses on the stack (a single linked list). At the end of the sentence (say the word from '.') (I hope the memory is not over yet, but this can be checked along the way) printed out the stack. An interesting extension of the problem is the transition to the use of (VERY) large external memory when the RAM is depleted (generally speaking, the start of pumping modified pages into the swap). The comment is professional (non-teaching) character. - avp
      • scanf is bad, it is better to use strsep in a loop and inside to collect an array of strings (words). Then with the for cycle, turn the array on the back side. If the input data is very cool, then inside the loop you can write to the file, and only then read it, you can also from the end :) lseek - NewView