Header Ad

HackerRank Strings solution in c++ programming

In this HackerRank Strings problem in the c++ programming language, 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 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.

HackerRank Strings solution in c++ programming


HackerRank Strings problem solution in c++ programming.

#include <bits/stdc++.h>

using namespace std;

int main()
{
    string a, b;
    cin >> a >> b;
    
    cout << a.length() << ' ' << b.length() << endl;
    
    cout << a + b << endl;
    
    swap( a[0], b[0] );
    cout << a << ' ' <<  b << endl;
    
    return 0;
}


Second solution

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

int main() {
    string a,b;
    char A,B;
    cin>>a;
    cin>>b;
    cout << a.length() << " " << b.length() << "\n";
    cout << a << b << "\n";
    A = a[0];
    B = b[0];
    a[0] = B;
    b[0] = A;
    cout << a << " " << b << "\n";
  
    return 0;
}

Post a Comment

0 Comments