Kevin
Kevin

Reputation: 13

Switching elements of two strings C++

I wanted to know if it was possible to switch two exact elements of two different (but same length) strings? Im trying to switch every occurrence of a letter in a string to the second string. For example

string x = "cis";
str1 = "coding is so great";
str2 = "______ __ __ _____";    

I want to read in string x, and letter by letter swap every occurrence of said letter from str1 into the exact position to str2 so after each loop they become

str1 = "_od_ng _s _o great";

and

str2 = "c__i__ is s_ _____";

Its all over the place and hard to read but this is my program so far

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <algorithm>

using namespace std;

int main(){
int numClues = 5;
int numHints = 5;
string x, Answer = "coding is so great";
string inputAnswer = "______ __ __ _____";
string Clues[5] = {"sin", "god", "cis", "at", "gore"};

cout<<Answer<<endl;
cout<<inputAnswer<<endl;
cout<<"Enter a clue: \n";
cin>>x;
    for(int i = 0; i<numClues; i++) // For loop to go through the clues and see if the correct answer matches any of the clues.
    {
        if(x == Clues[i])
           {
               string temp = Clues[i];
               for(int j=0; j<Clues[i].length(); j++)   // For loop to read each letter of clue
               {
                for(int y=0; y<Answer.length(); y++) //For loop to read in Answer string letter by letter
                if (Answer.find(temp[j]))  // If letter of Answer is equal to letter of clue 
                   {                                
                           cout<<temp[j]<<"\n";
                           break;
                   }
               }
           }
    }

cout<<inputAnswer<<endl;
cout<<Answer;

return 0;
}

I understand it would probably be easier to code using another container like a vector but if theres a way to do it simply using string functions that'd be awesome since this is just a portion of a group project.

Upvotes: 1

Views: 138

Answers (1)

Masked Man
Masked Man

Reputation: 11075

Your code seems way too complicated than what is necessary (unless I am missing some other requirement which you haven't specified in the question). The following code should do what you are looking for.

for (auto it1 = str1.begin(), it2 = str2.begin()
        ; it1 != str1.end() && it2 != str2.end()
        ; ++it1, ++it2) {  // iterate over both the strings in lockstep
    if (x.find(*it1) != std::string::npos) {  // if the char in str1 is in "Clues" ...
        std::swap(*it1, *it2);  // ... then swap it with respective char in str2
    } 
}

Demo on Ideone: Link

To compare against each element of the array of Clues, you just run the above if() statement through a loop, which I am sure you are capable of doing.

Upvotes: 1

Related Questions