Skip to content
the poor coder

Hackerrank Strings Solution

Poor Man
Published
Updated
Reading time
2 min read

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:

Declaration:

Text
string a = "abc";

Size:

Text
int len = a.size();

Concatenate two strings:

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

Accessing  element:

Text
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,  and , 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  and  respectively.
In the second line print the string produced by concatenating  and  ().
In the third line print two strings separated by a space,  and .  and  are the same as  and , respectively, except that their first characters are swapped.

Sample Input

Text
abcd
ef

Sample Output

Text
4 2
abcdef
ebcd af

Explanation

  • "abcd"
  • "ef"
  • "abcdef"
  • "ebcd"
  • "af"

Solution in cpp#

Approach 1.

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

int main() {
 string a,b;
    char temp;
    cin>>a>>b;
    cout<<a.size()<<' '<<b.size()<<endl;
    cout<<a+b<<endl;
    temp=a[0];
    a[0]=b[0];
    b[0]=temp;
    cout<<a<<' '<<b;
  
    return 0;
}

Approach 2.

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

int main() {
  string a,b;
    char i,j;
    int c,d;
   cin>>a;
    cin>>b;
  c=a.size();
    d=b.size();
    cout<<c<<" "<<d<<"\n";
     cout<<a+b<<"\n";
    i=b[0];
   b[0]=a[0];
    a[0]=i;
    cout<<a<<" ";
    cout<<b;
    return 0;
}

  

Approach 3.

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

int main() {
    std::string a, b;
    std::cin >> a >> b;
    
    std::cout << a.size() << " " << b.size() << std::endl
              << a + b << std::endl;
    
    std::swap(a[0], b[0]);
    std::cout << a << " " << b;
    
    return 0;
}

Keep going

2020

Hackerrank StringStream Solution

stringstream is a stream class to operate on strings. It basically implements input/output operations on memory (string) based streams. stringstream can be helpful in different type of parsing. The following…

2020

Hackerrank Common Child Solution

A string is said to be a child of a another string if it can be formed by deleting 0 or more characters from the other string. Given two strings of equal length, what's the longest string that can be constructed such…

ESC