This seems like your homework, but I will do it for you and explain you the steps. My output is:
cumpatir
#include <iostream>
#include <string>
using namespace std;
string rotate_vowels(const string& s)
{
string copy_of_s = s;
char vow[] = { 'a', 'e', 'i', 'o', 'u' };
const size_t size_of_vowels = 5;
for(size_t i = 0; i < copy_of_s.length(); i++)
{
for(size_t j = 0; j < size_of_vowels; j++)
{
if (s[i] == vow[j])
{
copy_of_s[i] = vow[ (j + 1) % size_of_vowels]; //make sure you dont access the element after u, which does not exist
break;
}
}
}
return copy_of_s;
}
int main()
{
string p = "computer";
cout << rotate_vowels(p) << endl;
}
Explanation:
#include <iostream>
#include <string>
This part tells the compiler which functions and classes to use. In this case the input / output functions (iostream) and the string functions.
using namespace std;
This makes sure you don't have to use std::string and you can just write string.
string rotate_vowels(const string& s)
If you don't change a value make it const. It make your programm run faster and you can not change it be accident.
const size_t size_of_vowels = 5;
Use variables for the size of arrays. Even better use Vectors since you are in C++ or use this MAKRO if you like C Style coding. Common array length macro for C?
for(size_t i = 0; i < copy_of_s.length(); i++)
Use size_t instead of int. size_t is like an int but it can't get negative. And on almost on Plattforms (x86, arm, etc.) it is way bigger than int, so it is safer to use.
break;
Use break to end the vowel loop, when a replacement was found (like a becomes an e).
copy_of_s[i] = vow[ (j + 1) % size_of_vowels]; //make sure you dont access the element after u, which does not exist
This line is tricky. You have 5 Vowels char vow[] = { 'a', 'e', 'i', 'o', 'u' };. vow[0] is 'a', vow[4] is 'u'. What happens you have vow[4+1]? You would access vow[5] which does not exist. This can lead to a crash or random data which confuses your programm. To solve this problem you can use
vow[(4+1)%5]
The is a division where you only keep the remainder. Sounds complicated but is quite easy. 3 % 5 = 0 remainder 3 (the 5 fits zero times into the 3). 5 % 5 = 1 Remainder 0 (the 5 fits one time into the 5, but nothing is left). 7 % 5 = 1 Remainder 2 (you get the idea).
You ignore the 1 in 7 % 5 = 1 Remainder 2, and just keep the two. So the result for 7 % 5 is 2. This way you can "wrap around" your array index and never access vow[5]. Because vow[5%5] is vow[0], so your 'u' becomes an 'a'.