String Merge Read in two strings (no spaces in either). Print the characters of
ID: 639928 • Letter: S
Question
String Merge
Read in two strings (no spaces in either). Print the characters of each string in alternating fashion, starting with the longest string. If they are the same length, use the first string read in first.
Samples:
Hints: you only want one loop for this... both first chars, both second chars... Just be careful you don't try to print characters in the shorter string once you are done with it!
Using .at( ) instead of [ ] will help make sure that your program blows up if you go past the end of a string instead of just doing something unpredictable or printing garbage ASCII characters that may not be visible.
This code is in c++
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
int main(){
string first, second;
cout << "Input: ";
cin >> first >> second;
if(first.size() < second.size()){
string temp = first;
first = second;
second = temp;
}
cout << "Output: ";
int flag = 0, count1 = 0, count2 = 0;
for(int i = 0; i < first.size() + second.size(); ++i){
if((flag == 0 || flag == 4) && flag != 3){
if(count1 < first.size()){
cout << first[count1++];
}
else{
flag = 3;
cout << second[count2++];
}
flag = 1;
}
else{
if(count2 < second.size()){
cout << second[count2++];
}
else{
flag = 4;
cout << first[count1++];
}
flag = 0;
}
}
return 0;
}