Strings in C++ | HackerRank Solution

What’s up coderz, Today we will be solving Strings in C++ HackerRank Solution.

Strings in C++ HackerRank Solution


C++ provides a nice alternative data type to manipulate strings, and the data type is conveniently called string. Some of its widely used features are the following:


 string a = "abc";


    int len = a.size();

Concatenate two strings:

 string a = "abc";
    string b = "def";
    string c = a + b; // c = "abcdef".

Accessing ith element:

 string s = "abc";
    char   c0 = s[0];   // c0 = 'a'
    char   c1 = s[1];   // c1 = 'b'
    char   c2 = s[2];   // c2 = 'c'

    s[0] = 'z';         // s = "zbc"

P.S.: We will use cin/cout to read/write a string.

Input Format

You are given two strings, a and b, separated by a new line. Each string will consist of lower case Latin characters (‘a’-‘z’).

Output Format

In the first line print two space-separated integers, representing the length of a and b respectively.

In the second line print the string produced by concatenating a and b (a+b).

In the third line print two strings separated by a space, a’ and b’. a’ and b’ are the same as a and b, respectively, except that their first characters are swapped.

Sample Input


Sample Output

4 2
ebcd af


  • a = “abcd”
  • b = “ef”
  • |a| = 4
  • |b| = 2
  • a + b = “abcdef”
  • a’ = “ebcd”
  • b’ = “af”

Solution – Strings in C++ HackerRank Solution

#include <iostream>
#include <string>
using namespace std;

int main() {
	// Complete the program
    string a,b;
    cin >> a >> b ;
    int l_of_a = a.size();
    int l_of_b = b.size();
    cout << l_of_a <<" "<<l_of_b << endl;
    cout << a << b << endl;
    char c1 = a[0];
    char c2 = b[0];
    a[0] = c2;
    b[0] = c1;
    cout << a <<" "<<b;
    return 0;
Strings in C++ HackerRank Solution
Strings in C++ HackerRank Solution

Disclaimer: The above Problem (Strings in C++) is generated by Hacker Rank but the Solution is provided by CodingBroz.

Broz Who Code


Leave a Comment

Your email address will not be published.