Basic String Programs in C++
1. Reverse a String
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cout << "Enter a string: ";
getline(cin, str);
int n = str.length();
for (int i = 0; i < n / 2; i++) {
swap(str[i], str[n - i - 1]);
}
cout << "Reversed string: " << str;
return 0;
}
2. Check if a String is a Palindrome
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
int start = 0, end = str.length() - 1;
bool isPalindrome = true;
while (start < end) {
if (str[start] != str[end]) {
isPalindrome = false;
break;
}
start++;
end--;
}
if (isPalindrome)
cout << "It is a palindrome.";
else
cout << "It is not a palindrome.";
return 0;
}
3. Count Vowels and Consonants
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cout << "Enter a string: ";
getline(cin, str);
int vowels = 0, consonants = 0;
for (char ch : str) {
if (isalpha(ch)) {
char lower = tolower(ch);
if (lower == 'a' || lower == 'e' || lower == 'i' || lower == 'o' || lower ==
'u')
vowels++;
else
consonants++;
}
}
cout << "Vowels: " << vowels << "\n";
cout << "Consonants: " << consonants;
return 0;
}
7. Count Number of Words in a String
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cout << "Enter a sentence: ";
getline(cin, str);
int wordCount = 0;
bool inWord = false;
for (char ch : str) {
if (isspace(ch)) {
inWord = false;
} else if (!inWord) {
wordCount++;
inWord = true;
}
}
cout << "Number of words: " << wordCount;
return 0;
}
8. Remove Duplicate Characters from String
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
string result = "";
unordered_set<char> seen;
for (char ch : str) {
if (seen.find(ch) == seen.end()) {
result += ch;
seen.insert(ch);
}
}
cout << "String after removing duplicates: " << result;
return 0;
}
10. Check if Two Strings are Anagrams
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string str1, str2;
cout << "Enter first string: ";
cin >> str1;
cout << "Enter second string: ";
cin >> str2;
sort(str1.begin(), str1.end());
sort(str2.begin(), str2.end());
if (str1 == str2)
cout << "Strings are anagrams.";
else
cout << "Strings are not anagrams.";
return 0;
}
15. Print All Substrings of a String
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
int n = str.length();
for (int i = 0; i < n; i++) {
for (int len = 1; len <= n - i; len++) {
cout << str.substr(i, len) << endl;
}
}
return 0;
}