Palindrome
#include <iostream>
using namespace std;
bool palin(string word){
string rw("");
//sol #1
for (int x=0; x<word.size();x++)
{
rw = word[x] + rw; // ex: home= h, oh, moh, emoh
}
//sol #2
/*
for (int x=word.size()-1; x>=0 ;x--)
{
rw = rw + word[x]; // ex: home= e, em, emo, emoh
}
*/
return (rw==word);
//if (rw==word)
// return true;
//return false;
}
int main(){
string w;
cin >> w;
if (palin(w))
{
cout<<w<< " is a palindrome"<<endl;
}
else
{
cout<<w<< " is NOT a palindrome"<<endl;
}
return 0;
}
Strings methods:
#include <string>
#include <iostream>
using namespace std;
int main(){
string s("hello world");
cout<<s.find("l")<<endl; //2
cout<<s.rfind("l")<<endl; //9
cout <<s.substr(6,3)<<endl; //wor
if (s.find("xx") == string::npos) //true
{
cout<< "not found"<<endl;
}
cout<<s[9]<<endl; //no error
cout<<s.at(9)<<endl;//runtime bounds checking error occurs
cout<<s<<endl;
return 0;
}
Replace all occurances of a sub string in a string
#include <iostream>
using namespace std;
//this program will replace a substring in a user input string
//this code works even when the new string has the old string in it
int main()
{
string s;
string ow;
string nw;
cout << "Enter a sentence: ";
getline(cin, s);
cout << "Enter a word to delete: ";
getline(cin, ow);
cout << "Enter another word which replaces the deleted word: ";
getline(cin, nw);
size_t pos(0);
while ( (pos = s.find(ow, pos)) != string::npos )
{
s.replace( pos, ow.size(), nw);
pos = pos + nw.size();
}
cout << s << endl;
return 0;
}