I'm a beginner in c and I'm training on exercises.
I'm stuck on one part. I would like to insert the string "CH" in front of each vowel in a sentence.
I first tried using string::replace, but it was not the best idea. I would like to use string::insert to do this.
However, I can't seem to use it properly in a loop to tell it that the [i] is the desired position
Do you have any advice for me?
string message = "you have a secret message to decrypt";
string newMessage = "";
string InsertMessage = "CH";
for (int i = 0; i < message.length(); i ) {
if (
message[i] == 'a' ||
message[i] == 'e' ||
message[i] == 'i' ||
message[i] == 'o' ||
message[i] == 'u' ||
message[i] == 'y')
{
//newMessage = message.replace(i, 1, InsertMessage);
newMessage = message.insert(i, InsertMessage);
}
}
cout << newMessage << endl;
return 0;
CodePudding user response:
This statement
newMessage = message.insert(i, InsertMessage);
does not make a sense at least because it changes the original string message.
I can suggest the following approach shown in the demonstration program below.
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
int main()
{
std::string message = "you have a secret message to decrypt";
std::string newMessage;
std::string InsertMessage = "CH";
const char *vowels = "aeiouy";
auto n = std::count_if( std::begin( message ), std::end( message ),
[vowels]( const auto &c ) { return std::strchr( vowels, c ); } );
newMessage.resize( message.size() n * InsertMessage.size() );
std::string::size_type pos = 0;
do
{
auto i = message.find_first_of( vowels, pos );
if (i == std::string::npos)
{
newMessage = message.substr( pos );
pos = i;
}
else
{
newMessage = message.substr( pos, i - pos );
newMessage = InsertMessage;
pos = i;
newMessage = message[pos ];
}
} while( pos != std::string::npos );
std::cout << newMessage << '\n';
}
The program output is
CHyCHoCHu hCHavCHe CHa sCHecrCHet mCHessCHagCHe tCHo dCHecrCHypt
CodePudding user response:
Thanks for your answers, I'll work on it :)