Check and recruit programming questions -- inverted string

Posted by doox00 on Sun, 26 Apr 2020 17:38:02 +0200

Turn the words of a sentence upside down, without turning the punctuation upside down. For example, I like beijing. After the function, it becomes: beijing. like I

Enter a description:

Each test input contains one test case: I like beijing. The input case length shall not exceed 100 < / pre >

Output Description:

Output the inverted string in turn, and split it with space
Example 1

input

I like beijing.

output

beijing. like I

thinking

First, reverse the whole string, and then reverse each word, mainly testing the hard coding ability.

Specific implementation code

#include <iostream>
#include <string>

using namespace std;
typedef long long LL;

void reverse(string &s) {
    int length = s.size();
    for (int i = 0; i < length / 2; i++) {
        char temp = s[i];
        s[i] = s[length - 1 - i];
        s[length - 1 - i] = temp;
    }
}

void reversed(string &s) {
    reverse(s);
    int length = s.size(), start = 0,end = 0;
    //cout << s << endl;
    bool flag = true;
    for (int i = 0; i < length; i++) {
        if (s[i] == ' ' && flag) {
            string temp = s.substr(start, i - start  );
            //cout << temp << endl;
            reverse(temp);
            s.replace(start, i - start, temp);
            flag = false;
        }
        else if (!flag) {
            start = i;
            flag = !flag;
        }
    }
    string temp = s.substr(start, length - start);
    //cout << temp << endl;
    reverse(temp);
    s.replace(start , length - start, temp);
}


int main() {
    ios::sync_with_stdio(false);
    string s;
    getline(cin, s);
    reversed(s);
    cout << s << endl;
    system("pause");
    return 0;
}


My implementation is a bit stupid, but I have practiced the use of string class. reverse can use libraries, and substr functions can also be used. The end and start variables are also redundant.
Here is the code written by the simplified version of the big guy!

Link:[https://www.nowcoder.com/questionTerminal/ee5de2e7c45a46a090c1ced2fdc62355](https://www.nowcoder.com/questionTerminal/ee5de2e7c45a46a090c1ced2fdc62355)
//Source: niuke.com
int main() {
    string str;
    while (getline(cin, str)) {
        reverse(str.begin(), str.end());
        int i = 0, j = i;
        while (i<str.size()) {
            while (i<str.size() && str[i] == ' ')
                ++i;
            j = i;
            while (i<str.size() && str[i] != ' ')
                ++i;
            reverse(str.begin() + j, str.begin() + i);
            j = i;
        }
        cout << str << endl;
    }
    return 0;
}


Topics: iOS