Feb 4, 2010 at 9:06am UTC
program no.1 ==this program should accept both string and a single character from the user. The program should determine how many times the character is contained in the string.==
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main()
{
string str;
char chr;
int i=0, ctr=0;
cout << "Enter a string: ";
getline(cin, str);
cout << "Enter a charter: ";
cin >> chr;
while (i < str.length())
{
if (i = str.find(chr))
ctr++;
i++;
}
cout << "There are " << ctr << chr << "in the string " << endl;
getch();
return 0;
}
program no.2 == This program accepts a string from the user and then replaces all occurrences of the letter "e" with the letter "x".
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main()
{
string str;
int i=0;
cout << "Enter a string:";
getline (cin, str);
while (i < str.length())
{
i= str.find("e");
str.replace(i, 1, "x");
i++;
}
cout << str <<endl;
return 0;
}
Feb 4, 2010 at 10:27am UTC
Hi,
In your first program i = str.find(chr)
will return the first occurence of the character in the string.
Now the while loop will never end in case where character is at found in any location other than last location.
Last edited on Feb 4, 2010 at 10:30am UTC
Feb 4, 2010 at 11:17am UTC
@ankushnandan
@Denis
thanks to your help guys! it's a success! :)