How to reverse a given sentence (string) in C ++?

Example: if the input was DOG, HOW KATS output - CATS LIKE DOGS

consider that I should use only: If-else conditions, while for loops, arrays, strings, and functions. NOT string functions, pointers and dynamic allocation of memory and structure. Spaces should be the same as in the example.

I tried to do the following, but it does not work, can you help?

void revSent(char str[]){
char temp[100];
int k;
for (i=sentenceSize ; i>0 ; i--)
    for (k=0 ; k<sentenceSize ; k++)
        temp[k]=str[i];

for (k=0 ; k<sentenceSize ; k++)
    if (temp[k]!=' ')
        for (i=k ; i>0 ; i--)
            printf("%c", temp[i]);

}
+3
source share
6 answers

It is easy to do this in place, without any additional data structures:

  • cancel the whole line: DOGS LIKE CATSSTAC EKIL SGOD

  • cancel each word in the line: STAC EKIL SGODCATS LIKE DOGS

: (1), (2).

+9

, :

  • .
  • .
  • , .
+5

, , :

std::vector<std::string> sentence;
std::copy(std::istream_iterator<std::string>(std::cin),
          std::istream_iterator<std::string>(),
          std::back_inserter(sentence));
std::reverse(sentence.begin(), sentence.end());

, , , , std::reverse(), .

, , . , . , - , , , , .

+3

: , Paul OJ. , .

+2
  • / / /.

Voila!

0

, STL ?

, , .

:

while (original_string isn't empty){    
   take first word  
   prepend to reversed string
}

++ ( find substr, )

    using namespace std;
string word_reverse(string original){
    string reverse_string;
    if (original.find(' ')!=string::npos){
        do{
            int pos=original.find(' ');
            //prepend word
            reverse_string=original.substr(0,pos)+' '+reverse_string;
            //remove word from original,considering the found whitespace
            original=original.substr(pos+1,original.length()-(pos+1));
        }while(original.find(' ')!=string::npos);
        //don't forget the last word!
        return original+' '+reverse_string;
    }
    else{//no whitespace: return original text
        return original;
    }
}
0

Source: https://habr.com/ru/post/1776563/


All Articles