HackerRank Problem : Reverse and capitalise first alphabet of each word.


 Problem : (Link : Click here to visit this problem on HackerRank. )


Reverse the words in a string and capitalize the first letter of each reversed word, preserving the capitalization in the original stri. For eg: "Hello World" would be transformed to "OlleH DlroW".

Input :

The first line of input would be the number of test cases followed by each string in a line.

Output :

Output should be the string with each word reversed and first letter of each reversed word capitalized. Each output string should be printed to a new line.

  Sample Input

Sample Output
1
Hello World
OlleH DlroW

------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Solution : ( in C++ )

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
int main()
{
    int x;
    cin >> x;

    for (int i = 0; i < x; i++) {
        string line;
        getline(cin, line);
  
                  /* this is required to eliminate trailing whitespaces created due to  endline character of cin>> 
*/    
        
        getline(cin, line);

        //loop for reversing words
        int j = 0;
        for (int i = 0; i <= line.length(); i++)
            if (line[i] == ' ' || line[i] == '\0') {

                reverse(line.begin() + j, line.begin() + i);
                line[j] = toupper(line[j]);
                j = i + 1;
            }

        cout << line << endl;
    }
    return 0;
}

Comments

Popular posts from this blog

CodeChef : Breaking Bricks || Problem Code: BRKBKS

LeetCode: 169 Majority Element