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;
}

 65 total views,  3 views today

Post Disclaimer

the above hole problem statement is given by hackerrank.com but the solution is generated by the SLTECHACADEMY authority if any of the query regarding this post or website fill the following contact form thank you.

Leave a Reply

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