Strings – HackerRank Solution

Strings – HackerRank Solution

Problem :

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 :
string a = "abc";
  • Size :
int len = a.size();
  • Concatenate two strings :
string a = "abc";
string b = "def";
string c = a + b; // c = "abcdef".
  • Accessing i^th 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.

Sample Input :

abcd
ef

Sample Output :

4 2
abcdef
ebcd af

Solution :

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

int main() {
    string a, b;
    cin >> a >> b;

    int lena = a.size();
    int lenb = b.size();
    cout << lena << " ";
    cout << lenb << endl;

    string sum = a + b;
    cout << sum << endl;

    char c = a[0];
    char d = b[0];
    a[0] = d;
    b[0] = c;
    cout << a << " " << b;

  
    return 0;
}

 188 total views,  1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *