C++ program to get length of strings, perform concatenation and swap characters

C++Server Side ProgrammingProgramming

Suppose we have two strings s and t, we shall have to find output in three lines, the first line contains lengths of s and t separated by spaces, the second line is holding concatenation of s and t, and third line contains s and t separated by space but their first characters are swapped.

So, if the input is like s = "hello", t = "programmer", then the output will be

5 10
pello hrogrammer

To solve this, we will follow these steps −

  • display length of s then print one space and length of t

  • display s + t

  • temp := s[0]

  • s[0] := t[0]

  • t[0] := temp

  • display s then one blank space and display t


Let us see the following implementation to get better understanding −

#include <iostream>
using namespace std;
int main(){
    string s = "hello", t = "programmer";
    cout << s.length() << " " << t.length() << endl;
    cout << s + t << endl;
    char temp = s[0];
    s[0] = t[0];
    t[0] = temp;
    cout << s << " " << t << endl;


"hello", "programmer"


5 10
pello hrogrammer
Published on 07-Oct-2021 07:37:09