You are on page 1of 3

8.

) [15 points] Write a function randomHobbit which returns the name of one of the
four hobbits listed below at random:
Frodo Sam Pippin Merry
All four names should be equally likely to be returned. To receive full credit, you must
use a switch statement. An example call to the function is given below.
srand ( (int) time(0) );
cout << "A random hobbit is " << randomHobbit( ) << ".\n";
string randomHobbit( ) {
int r = 1+rand()%4;
switch (r) {
case 1: return "Frodo"; break;
case 2: return "Sam"; break;
case 3: return "Pippin"; break;
case 4: return "Merry"; break;
}

OUTPUT SORULARI

string c = "hi";
while (c.length() < 6) {
c += c;
cout << c << "\n";
}

hihi
hihihihi

string d = "gandalf";
d.insert(0,"hello");
d.erase(3,5);
cout << d;
heldalf

C++ String Sınıfı Sayfa 1 / 3


Write a function replaceVowels that takes a string as input and replaces every lowercase
vowel (aeiou) with an one of the four symbols below:
*&#@
The symbol used should be selected at random. A sample run is shown below.
cout << replaceVowels ("Frodo, look out for the orcs!!!");
Output: Fr&d*, l#*k *@t f&r th# &rcs!!!

string replaceVowels (string s)


{
int r; //Random number.
for (int i=0; i < s.length( ); i++)
{
if ( s[i] == ‘a’ || s[i] == ‘e’ || s[i] == ‘i’
|| s[i] == ‘o’ || s[i] == ‘u’)
{
r = 1 + rand( ) % 4;
if (r==1)
s[i] = ‘*’;
else if (r==2)
s[i] = ‘&’;
else if (r==3)
s[i] = ‘#’;
else
s[i] = ‘@’;
}
}
return s;
}

C++ String Sınıfı Sayfa 2 / 3


Write a full program, starting from #include, that asks the user to
enter a single letter and then a phrase. The program should then report how many times
that letter occurred in the phrase, displaying the letter with double quotes around it. An
example is shown below where the user searched for lower-case "o".
Enter letter: o
Enter phrase: The Lord Of The Rings is cool!
The letter "o" occurred 3 times.
Your program does not have to check upper versus lower case, note the capital "O" in the
example above was not counted.

#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Enter letter: ";
string letter;
cin >> letter;
cout << "Enter phrase: ";
string phrase;
getline(cin,phrase);
int count = 0;
for (int i=0; i<phrase.length(); i++)
if (phrase.substr(i,1) == letter)
count++;
cout << "The letter \""
<< letter
<< "\" occurred "
<< count
<< " times.\n";
return 0;
}

C++ String Sınıfı Sayfa 3 / 3

You might also like