Problem statement:
Given two strings, we need to perform various string operations such as finding the length, concatenation, swapping characters, and printing specific substrings.
Sample Input:
The input consists of two strings on separate lines.
abcd
efgh
Sample Output:
Print the length of each string, the concatenation of the strings, swap the first character of each string and print them, and print the substring of each string.
4 4
abcdefgh
ebcd afgh
Explanation:
In this example, the input strings are "abcd" and "efgh". We need to perform the following operations:
Calculate the length of each string: "abcd" has a length of 4, and "efgh" also has a length of 4.
Concatenate the strings: "abcd" + "efgh" = "abcdefgh".
Swap the first characters of each string: "efgh" + "abcd" = "ebcd afgh".
Print the substring of each string: "abcd" is the substring of "abcdefgh", and "efgh" is the substring of "ebcd afgh".
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1, str2;
getline(cin, str1);
getline(cin, str2);
// Calculate the length of each string
int len1 = str1.length();
int len2 = str2.length();
// Concatenate the strings
string concatenated = str1 + str2;
// Swap the first characters of each string
swap(str1[0], str2[0]);
// Print the results
cout << len1 << " " << len2 << endl;
cout << concatenated << endl;
cout << str1 << " " << str2 << endl;
cout << str1.substr(1) << " " << str2.substr(1) << endl;
return 0;
}
Code Explanation
Explanation of the Solution:
We start by reading the two input strings using getline(cin, str1) and getline(cin, str2).
We calculate the length of each string using the length() function and store them in variables len1 and len2.
We concatenate the strings using the + operator and store the result in the concatenated string.
We swap the first characters of each string using the swap() function, which swaps the characters in-place.
Finally, we print the results:
We print the length of each string using cout << len1 << " " << len2 << endl.
We print the concatenated string using cout << concatenated << endl.
We print the swapped strings using cout << str1 << " " << str2 << endl.
We print the substrings of each string starting from the second character using cout << str1.substr(1) << " " << str2.substr(1) << endl.
This solution demonstrates various string operations such as calculating the length, concatenation, character swapping, and printing substrings using the string class in C++.
I hope this solution and explanation are helpful!