This article provides a comprehensive set of 27 practical C++ string exercises, structured into Beginner, Intermediate, and Advanced levels.
Each exercise includes a clear problem statement, a helpful hint, a complete C++ solution, and a detailed explanation. This ensures you not only solve the problem but deeply understand why the solution works.
What You Will Practice:
The exercises cover the following string topics:
- Fundamentals & Manipulation: String length, concatenation, indexing, basic I/O, case conversion, and in-place modification.
- Analysis & Utility: Character frequency counting, word tokenization, and managing unique characters.
- Searching: Substring searching, simple pattern matching, and lexicographical comparison.
- Algorithms: Implementing core logic like String Reversal, Run-Length Encoding (RLE), Anagram checking, and URLify.
- Advanced Techniques: Implementing
atoi(with overflow handling), Permutations using recursion, Longest Palindromic Substring, and usingstd::stackfor Valid Parentheses.
+ Table Of Contents
Table of contents
- Exercise 1: String Length
- Exercise 2: String Concatenation
- Exercise 3: Character Access
- Exercise 4: Character Check
- Exercise 5: String Copy
- Exercise 6: Reverse String
- Exercise 7: Count Vowels/Consonants
- Exercise 8: Case Conversion
- Exercise 9: Remove Spaces
- Exercise 10: Palindrome Check (Simple)
- Exercise 11: Word Count
- Exercise 12: Find Substring
- Exercise 13: Replace Substring
- Exercise 14: Frequency of Characters
- Exercise 15: Anagram Check
- Exercise 16: Check for Digit/Letter Only
- Exercise 17: Count Specific Word
- Exercise 18: Sort Characters
- Exercise 19: Lexicographical Comparison
- Exercise 20: Title Case
- Exercise 21: Remove Duplicates
- Exercise 22: String Rotation Check
- Exercise 23: Combine First/Last Characters
- Exercise 24: Longest Common Prefix
- Exercise 25: All Substrings
- Exercise 26: Permutations
- Exercise 27: Longest Palindromic Substring
Exercise 1: String Length
Problem Statement: Write a C++ program that prompts the user to enter a string and then calculates and prints the total number of characters in that string (its length).
Expected Output:
Enter a string: PYnative.com
The length of the string is: 12
+ Hint
The std::string class provides a built-in method, often named length() or size(), that efficiently returns the length of the string.
+ Show Solution
#include <iostream>
#include <string>
int main() {
std::string user_string;
// Prompt the user for input
std::cout << "Enter a string: ";
// Read the entire line, including spaces
std::getline(std::cin, user_string);
// Calculate the length
int length = user_string.length();
// Print the result
std::cout << "The length of the string is: " << length << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The solution uses
std::stringto store the user’s input. - The
std::getline(std::cin, user_string)function is essential here as it allows the program to read the entire line of input, including spaces, until the user presses Enter. - Finally, the
.length()method of thestd::stringobject is called to retrieve and display the character count.
Exercise 2: String Concatenation
Problem Statement: Write a C++ program that takes two separate strings as input from the user and then combines (concatenates) them into a single new string, printing the result.
Expected Output:
Enter the first string: C++
Enter the second string: Programming
The combined string is: C++ Programming
+ Hint
C++ overloaded the addition operator (+) for std::string objects. This operator allows you to easily join two strings together.
+ Show Solution
#include <iostream>
#include <string>
int main() {
std::string str1, str2;
// Get the first string
std::cout << "Enter the first string: ";
std::getline(std::cin, str1);
// Get the second string
std::cout << "Enter the second string: ";
std::getline(std::cin, str2);
// Concatenate the two strings using the '+' operator
std::string combined_string = str1 + " " + str2;
// Print the concatenated string
std::cout << "The combined string is: " << combined_string << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Two
std::stringvariables,str1andstr2, are read from the user. - The core operation is the use of the
+operator (str1 + " " + str2). - This operator creates a new
std::stringobject by appendingstr2tostr1, with an added space literal in between for readability, demonstrating simple string concatenation.
Exercise 3: Character Access
Problem Statement: Write a program to prints only the first character and the last character of a string.
Given:
std::string str = "PYnative";Code language: C++ (cpp)
Expected Output:
First character: P
Last character: e
+ Hint
Characters in a C++ string are accessed using square brackets ([]), similar to arrays. Remember that string indexing starts at 0 for the first character. The last character is at the index equal to the string’s length minus one.
+ Show Solution
#include <iostream>
#include <string>
int main() {
std::string str = "PYnative";
// Access the first character (index 0)
char first_char = str[0];
// Access the last character (index length - 1)
char last_char = str[str.length() - 1];
std::cout << "First character: " << first_char << std::endl;
std::cout << "Last character: " << last_char << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The characters are accessed using the array-like subscript operator
[]. The first character is always at index0(str[0]). - The length of the string is retrieved using
str.length(), and since indexing is zero-based, the last character’s index is calculated asstr.length() - 1. - A necessary check for an empty string (
str.empty()) is included to prevent an out-of-bounds error.
Exercise 4: Character Check
Problem Statement: Write a program to determine if the given character exists anywhere within the string and output a message indicating whether it was found or not.
Given:
std::string text = "PYnative";
char target_char = 't';Code language: C++ (cpp)
Expected Output:
SUCCESS: The character 't' was found at index 4.
+ Hint
- You can use a simple loop (like a
forloop) to iterate over every character in the string and compare it with the target character. - Alternatively, the
std::stringmethodfind()can be used, which returns a special value calledstd::string::nposif the character is not found.
+ Show Solution
#include <iostream>
#include <string>
int main() {
std::string text = "PYnative";
char target_char = 't';
// Use the find() method
size_t found_pos = text.find(target_char);
// The find() method returns std::string::npos if the character is not found
if (found_pos != std::string::npos) {
std::cout << "SUCCESS: The character '" << target_char
<< "' was found at index " << found_pos << "." << std::endl;
} else {
std::cout << "FAILURE: The character '" << target_char
<< "' was NOT found in the string." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
This solution utilizes the .find() method of the std::string class.
It searches for the target_char within the text string. If the character is found, find() returns the index of the first occurrence. If it is not found, it returns the constant std::string::npos (which stands for ‘no position’). The program checks the return value against std::string::npos to report the outcome.
Exercise 5: String Copy
Problem Statement: Write a program to demonstrate how to copy the contents of one std::string variable into another new std::string variable, and then print both variables to confirm the copy.
Given:
std::string original_string = "Hello, C++ World!";Code language: C++ (cpp)
Expected Output:
Original String (after modification): The original string has been changed.
Copied String (remains unchanged): Hello, C++ World!
+ Hint
In C++, the assignment operator (=) is overloaded for std::string objects. This allows for a simple and direct value copy, where the entire content of the source string is copied to the destination string.
+ Show Solution
#include <iostream>
#include <string>
int main() {
// 1. Define the source string
std::string original_string = "Hello, C++ World!";
// 2. Declare the destination string
std::string copied_string;
// 3. Perform the copy using the assignment operator
copied_string = original_string;
// 4. Modify the original string to prove it's a value copy
original_string = "The original string has been changed.";
// Print both strings
std::cout << "Original String (after modification): " << original_string << std::endl;
std::cout << "Copied String (remains unchanged): " << copied_string << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
C++ std::string implements value semantics, which means when you use the assignment operator (copied_string = original_string;), a deep copy of the character sequence is performed.
The copied_string now holds its own independent copy of the data “Hello, C++ World!”. The modification to the original_string afterward does not affect the copied_string, confirming a true copy was made.
Exercise 6: Reverse String
Problem Statement: Write a program that takes a string input from the user and prints a new string that contains the characters of the original string in reverse order.
Expected Output:
Enter a string to reverse: PYnative
Original string: PYnative
Reversed string: evitanYP
+ Hint
- You can use a loop that iterates backward from the last character of the original string (at index
length - 1) down to the first character (at index0), appending each character to a new, empty result string. - Alternatively, the standard library algorithm
std::reversecan be used on the string’s iterators.
+ Show Solution
#include <iostream>
#include <string>
#include <algorithm> // Required for std::reverse
int main() {
std::string str;
std::cout << "Enter a string to reverse: ";
std::getline(std::cin, str);
// Create a copy to reverse (optional, but good practice if you need the original)
std::string reversed_str = str;
// Use the std::reverse algorithm on the iterators
// str.begin() points to the first element
// str.end() points past the last element
std::reverse(reversed_str.begin(), reversed_str.end());
std::cout << "Original string: " << str << std::endl;
std::cout << "Reversed string: " << reversed_str << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
This exercise demonstrates the most idiomatic C++ way to reverse a sequence: using the std::reverse algorithm found in the <algorithm> header.
It takes two arguments: an iterator pointing to the beginning of the range to be reversed (reversed_str.begin()) and an iterator pointing one past the end of the range (reversed_str.end()). The algorithm efficiently swaps the characters in place within the reversed_str copy.
Exercise 7: Count Vowels/Consonants
Problem Statement: Write a program that accepts a string from the user and counts the total number of vowels (A, E, I, O, U, and their lowercase equivalents) and consonants within that string, ignoring spaces and punctuation.
Expected Output:
Enter a string: PYnative
Vowel Count: 3
Consonant Count: 5
+ Hint
- Iterate through the string one character at a time. For each character, first check if it is an alphabet letter using
std::isalpha(). If it is, convert it to lowercase usingstd::tolower()for easy comparison. - Then, use a series of
iforswitchstatements to check if the character is one of the five vowels. If it is an alphabet letter but not a vowel, it must be a consonant.
+ Show Solution
#include <iostream>
#include <string>
#include <cctype> // Required for tolower() and isalpha()
int main() {
std::string str;
int vowel_count = 0;
int consonant_count = 0;
std::cout << "Enter a string: ";
std::getline(std::cin, str);
for (char c : str) {
// 1. Check if the character is an alphabet letter
if (std::isalpha(c)) {
// 2. Convert to lowercase for easy comparison
char lower_c = std::tolower(c);
// 3. Check if it is a vowel
if (lower_c == 'a' || lower_c == 'e' || lower_c == 'i' || lower_c == 'o' || lower_c == 'u') {
vowel_count++;
}
// 4. If it is a letter but not a vowel, it's a consonant
else {
consonant_count++;
}
}
// Ignore spaces, digits, and punctuation
}
std::cout << "Vowel Count: " << vowel_count << std::endl;
std::cout << "Consonant Count: " << consonant_count << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
The solution uses a range-based for loop for clean iteration.
The crucial functions from the <cctype> header are: std::isalpha(c) to ensure only letters are processed, and std::tolower(c) to convert any uppercase letters to lowercase, simplifying the vowel check to only five comparisons (a, e, i, o, u). This logic correctly counts vowels and consonants while ignoring other characters like spaces or numbers.
Exercise 8: Case Conversion
Problem Statement: Write a program that takes a string input. Convert the entire string to all uppercase characters, print the result, and then convert the string to all lowercase characters and print that result.
Given:
std::string str = "PYnative C++ String Exercises";Code language: C++ (cpp)
Expected Output:
Original: PYnative C++ String Exercises
Uppercase: PYNATIVE C++ STRING EXERCISES
Lowercase: pynative c++ string exercises
+ Hint
- The C++ standard library provides functions
std::toupper()andstd::tolower()(in<cctype>) that operate on individual characters. - You will need to use the
std::transformalgorithm in combination with these functions to efficiently convert every character in the string.
+ Show Solution
#include <iostream>
#include <string>
#include <cctype> // For std::toupper and std::tolower
#include <algorithm> // For std::transform
int main() {
std::string str = "PYnative C++ String Exercises";
std::cout << "Original: " << str << std::endl;
// 1. Convert to UPPERCASE
std::string upper_str = str; // Make a copy
std::transform(upper_str.begin(), upper_str.end(), upper_str.begin(),
[](unsigned char c){ return std::toupper(c); });
std::cout << "Uppercase: " << upper_str << std::endl;
// 2. Convert to LOWERCASE
std::string lower_str = str; // Use the original again
std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(),
[](unsigned char c){ return std::tolower(c); });
std::cout << "Lowercase: " << lower_str << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
The most modern and efficient way to perform bulk character-by-character transformations is using the std::transform algorithm from the <algorithm> header.
This function applies a specified operation (in this case, std::toupper or std::tolower via a lambda function) to every element in the source range (defined by .begin() and .end() iterators) and stores the result back into the specified destination range (upper_str.begin()).
Exercise 9: Remove Spaces
Problem Statement: Write a program that accepts a string from the user and creates a new string that is identical to the original but with all whitespace characters removed.
Given:
std::string str = "This String Has Multiple Spaces.";Code language: C++ (cpp)
Expected Output:
Original string: "This String Has Multiple Spaces."
String without spaces: "ThisStringHasMultipleSpaces."
+ Hint
For an idiomatic C++ approach, combine the std::remove_if algorithm (using the predicate std::isspace) with the .erase() method. This allows you to remove characters in-place and resize the string efficiently.
+ Show Solution
#include <iostream>
#include <string>
#include <algorithm> // Required for std::remove_if
#include <cctype> // Required for std::isspace
int main() {
std::string str = "This String Has Multiple Spaces.";
std::cout << "Original string: \"" << str << "\"" << std::endl;
// 1. Use std::remove_if to move all unwanted characters (spaces) to the end
// The lambda function checks if a character is a space using std::isspace.
str.erase(
std::remove_if(str.begin(), str.end(),
[](unsigned char x){ return std::isspace(x); }),
str.end()
);
std::cout << "String without spaces: \"" << str << "\"" << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
This solution uses a standard library idiom: std::remove_if followed by .erase(). std::remove_if moves all characters that satisfy the predicate (i.e., spaces, checked by std::isspace) to the end of the string and returns an iterator to the new logical end of the valid data.
The .erase() method then uses this iterator to physically cut off the unwanted characters, resulting in an efficient in-place space removal.
Exercise 10: Palindrome Check (Simple)
Problem Statement: Write a program that prompts the user for a string and determines if it is a palindrome. A palindrome is a sequence of characters that reads the same forwards and backward (e.g., “madam” or “racecar”).
Expected Output:
Enter a string to check for palindrome: madam
"madam" IS a palindrome.
+ Hint
Use the std::reverse algorithm to reverse the cleaned string. Finally, compare the original string with the reversed string. If they are equal, it’s a palindrome.
+ Show Solution
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string original;
std::cout << "Enter a string to check for palindrome: ";
std::getline(std::cin, original);
// 2. Create the reversed copy
std::string reversed = original;
std::reverse(reversed.begin(), reversed.end());
// 3. Compare the cleaned original with the reversed copy
if (original.empty()) {
std::cout << "The string is empty." << std::endl;
}
else if (original == reversed) {
std::cout << "\"" << original << "\" IS a palindrome." << std::endl;
} else {
std::cout << "\"" << original << "\" IS NOT a palindrome." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
The std::reverse algorithm creates a reversed copy of this cleaned string. A simple equality check (clean_original == reversed) is then sufficient to determine if the string meets the palindrome criteria.
Exercise 11: Word Count
Problem Statement: Write a C++ program that accepts a sentence or paragraph as a string input from the user and calculates the total number of words present in the string. Assume words are separated by one or more whitespace characters.
Expected Output:
Enter a sentence or paragraph: PYnative c++ Exercises
Total word count: 3
+ Hint
The most robust way to count words is to count the transitions from a non-space character to a space character, or vice-versa.
A simpler approach is to use the std::stringstream class, which automatically treats whitespace as delimiters, allowing you to easily extract words one by one in a loop.
+ Show Solution
#include <iostream>
#include <string>
#include <sstream> // Required for std::stringstream
int main() {
std::string sentence;
int word_count = 0;
std::cout << "Enter a sentence or paragraph: ";
std::getline(std::cin, sentence);
// Create a stringstream object from the input string
std::stringstream ss(sentence);
// Temporary string to hold each extracted word
std::string word;
// The while loop extracts words until the stringstream is empty
while (ss >> word) {
word_count++;
}
std::cout << "Total word count: " << word_count << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The solution leverages the
std::stringstreamclass. Initializingsswith the input string places the string’s content into a stream buffer. - The expression
ss >> wordis the key: the stream extraction operator (>>) skips leading whitespace and reads characters until it encounters the next whitespace character, effectively extracting one word at a time into thewordvariable. - The loop continues and increments
word_countuntil the stream is empty.
Exercise 12: Find Substring
Problem Statement: Write a program that accepts a main string (the text) and a substring (the pattern) from the user. The program must find and print the starting index of the first occurrence of the substring within the main string. If the substring is not found, print a descriptive message.
Expected Output:
Enter the main text string: PYnative c++ Exercises
Enter the substring to search for: c++
Substring found!
Starting index: 9
+ Hint
- Use the
std::stringmethodfind(). This method takes the substring as an argument and returns the zero-based index of where the match begins. - If the substring is absent, it returns the special value
std::string::npos.
+ Show Solution
#include <iostream>
#include <string>
int main() {
std::string main_string;
std::string sub_string;
std::cout << "Enter the main text string: ";
std::getline(std::cin, main_string);
std::cout << "Enter the substring to search for: ";
std::getline(std::cin, sub_string);
// Use the find() method
size_t found_index = main_string.find(sub_string);
if (found_index != std::string::npos) {
std::cout << "Substring found!" << std::endl;
std::cout << "Starting index: " << found_index << std::endl;
} else {
std::cout << "Substring not found in the main text." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- This exercise is efficiently solved using the built-in
std::string::find()method. - The method returns a
size_tvalue, which is an unsigned integer type used for sizes and indices. If the substring is found,found_indexholds the index. - If it is not found,
found_indexholds the static constantstd::string::npos. Theifstatement checks for this condition to determine the output.
Exercise 13: Replace Substring
Problem Statement: Write a program that takes a text string, an old word (substring) to be replaced, and a new word (replacement string). The program must find the first occurrence of the old word and replace it with the new word, then print the modified string.
Given:
std::string text = "The quick brown fox jumps over the quick dog.";
std::string old_word = "quick";
std::string new_word = "slow";Code language: C++ (cpp)
Expected Output:
Original: The quick brown fox jumps over the quick dog.
Modified: The slow brown fox jumps over the slow dog.
+ Hint
- You can use the
std::stringmethodreplace(). - This method takes three arguments: the starting index of the replacement, the length of the substring to replace, and the replacement string itself.
- You will first need to find the starting index and the length of the old word.
+ Show Solution
#include <iostream>
#include <string>
int main() {
std::string text = "The quick brown fox jumps over the quick dog.";
std::string old_word = "quick";
std::string new_word = "slow";
std::cout << "Original: " << text << std::endl;
// Find the first occurrence of the old word
size_t pos = text.find(old_word);
// Loop to replace ALL occurrences
while (pos != std::string::npos) {
// Replace the old word with the new word
// Arguments: starting position, length of the text to replace, new text
text.replace(pos, old_word.length(), new_word);
// Find the next occurrence, starting immediately after the replacement
pos = text.find(old_word, pos + new_word.length());
}
std::cout << "Modified: " << text << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
This solution uses a while loop to find and replace all occurrences.
- Inside the loop,
text.find(old_word)locates the substring. The core operation istext.replace(). - After replacing, the next search (
text.find(old_word, pos + new_word.length())) is started from the character immediately following the newly inserted replacement word. - This prevents infinite loops in cases where the replacement word contains the old word.
Exercise 14: Frequency of Characters
Problem Statement: Write a program that counts the frequency (number of occurrences) of every unique character in an input string and prints the result only for characters that appeared one or more times. Ignore case and non-alphabetic characters.
Given:
std::string str = "Programming in CPP";Code language: C++ (cpp)
Expected Output:
string: Programming in CPP
Character Frequencies:
'a': 1
'c': 1
'g': 2
'i': 2
'm': 2
'n': 2
'o': 1
'p': 3
'r': 2
+ Hint
- This is an ideal problem for using a Hash Map (
std::unordered_map) or a Map (std::map), where the character is the key and the count is the value. - Iterate through the string, convert each character to lowercase using
std::tolower(), and increment its corresponding count in the map.
+ Show Solution
#include <iostream>
#include <string>
#include <map> // Required for std::map
#include <cctype>
int main() {
std::string str = "Programming in CPP";
std::map<char, int> char_counts;
std::cout << "Analyzing string: " << str << std::endl;
// 1. Iterate through the string and populate the map
for (char c : str) {
if (std::isalpha(c)) {
// Convert to lowercase and use as the map key
char_counts[std::tolower(c)]++;
}
}
// 2. Iterate through the map and print the results
std::cout << "Character Frequencies:" << std::endl;
for (const auto& pair : char_counts) {
std::cout << "'" << pair.first << "': " << pair.second << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The
std::map<char, int>container is used to store the frequency. The loop processes the input string character by character. - If a character is a letter (
std::isalpha), it’s converted to lowercase (std::tolower) to ensure case-insensitivity (e.g., ‘A’ and ‘a’ count together). - When a character is used as an index into the map (e.g.,
char_counts['a']++), if the key doesn’t exist, the map automatically inserts it with a default value of 0 before incrementing, making the counting process very concise.
Exercise 15: Anagram Check
Problem Statement: Write a function that takes two strings, str1 and str2, and returns true if they are anagrams of each other, and false otherwise. Two strings are anagrams if they contain the same characters with the same frequency (e.g., “listen” and “silent”). Ignore case and whitespace.
Given:
std::string s1 = "Astronomer";
std::string s2 = "Moon starer";Code language: C++ (cpp)
Expected Output:
"Astronomer" and "Moon starer" ARE anagrams.
+ Hint
- The most straightforward way to check for anagrams is to first clean both strings (remove spaces, convert to a single case) and then sort the characters of both cleaned strings.
- If the resulting sorted strings are identical, the originals were anagrams.
+ Show Solution
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
// Helper to clean and prepare the string
std::string clean_and_sort(const std::string& str) {
std::string result;
for (char c : str) {
if (std::isalpha(c)) {
result += std::tolower(c);
}
}
std::sort(result.begin(), result.end());
return result;
}
bool are_anagrams(const std::string& str1, const std::string& str2) {
return clean_and_sort(str1) == clean_and_sort(str2);
}
int main() {
std::string s1 = "Astronomer";
std::string s2 = "Moon starer";
if (are_anagrams(s1, s2)) {
std::cout << "\"" << s1 << "\" and \"" << s2 << "\" ARE anagrams." << std::endl;
} else {
std::cout << "\"" << s1 << "\" and \"" << s2 << "\" are NOT anagrams." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The core logic resides in the
clean_and_sorthelper function. This function iterates through a string, keeps only alphabetic characters, converts them to lowercase for case-insensitivity, and then usesstd::sort(from<algorithm>) to arrange all characters alphabetically. - Since anagrams are just rearrangements of the same characters, the two original strings are anagrams if and only if their sorted, cleaned versions are identical.
Exercise 16: Check for Digit/Letter Only
Problem Statement: Write a program that checks an input string to determine if it contains only alphabetic characters (letters) or only numeric characters (digits). If it contains any other character (like spaces or punctuation), or a mix of letters and digits, it should report that.
Given:
std::string s1 = "HelloWorld";
std::string s2 = "12345";
std::string s3 = "H3llo";Code language: C++ (cpp)
Expected Output:
HelloWorld Contains only letters.
12345 Contains only digits.
H3llo Contains a mix of characters and/or symbols.
+ Hint
- You need a
forloop and the functionsstd::isalpha()andstd::isdigit()from the<cctype>header. - Use a boolean flag for
is_all_lettersandis_all_digits. - Iterate through the string; if you find a non-letter, set
is_all_lettersto false. If you find a non-digit, setis_all_digitsto false.
+ Show Solution
#include <iostream>
#include <string>
#include <cctype> // Required for isalpha and isdigit
void check_content(const std::string& str) {
if (str.empty()) {
std::cout << "String is empty." << std::endl;
return;
}
bool all_letters = true;
bool all_digits = true;
for (char c : str) {
if (!std::isalpha(c)) {
all_letters = false;
}
if (!std::isdigit(c)) {
all_digits = false;
}
// Optimization: if both are false, we can stop early
if (!all_letters && !all_digits) {
std::cout << str <<" "<<"Contains a mix of characters and/or symbols." << std::endl;
return;
}
}
if (all_letters) {
std::cout << str <<" " <<"Contains only letters." << std::endl;
} else if (all_digits) {
std::cout << str <<" "<<"Contains only digits." << std::endl;
} else {
// This branch is rarely reached due to the optimization above
std::cout << str <<"Contains a mix of characters and/or symbols." << std::endl;
}
}
int main() {
std::string s1 = "HelloWorld";
std::string s2 = "12345";
std::string s3 = "H3llo";
check_content("HelloWorld");
check_content("12345");
check_content("H3llo");
return 0;
}Code language: C++ (cpp)
Explanation:
- The loop uses
std::isalpha(c)to check if a character is a letter andstd::isdigit(c)to check if it’s a digit. - For a string to be “all letters,” every character must satisfy
std::isalpha(). - By initializing both flags to
trueand setting them tofalsewhenever a character violates the condition, the function correctly determines the string’s composition upon loop completion.
Exercise 17: Count Specific Word
Problem Statement: Write a program that takes a sentence and a specific target word (substring) as input. The program should count how many times that exact whole word appears in the sentence. The search should be case-sensitive.
Given:
std::string sentence = "The cat sat on the mat. Cat, cat.";Code language: C++ (cpp)
Expected Output:
The word 'cat' appears 2 times.
+ Hint
- This requires iterating and searching. Use a loop combined with the
std::string::find()method to locate the starting position of the target word. To ensure it’s a whole word, check the characters immediately before and after the found position to see if they are non-alphabetic (spaces, punctuation, or string boundaries). - Remember that
std::string::find()can take a second argument to specify the starting position for the next search.
+ Show Solution
#include <iostream>
#include <string>
#include <cctype> // For isalpha
int count_word_occurrences(const std::string& text, const std::string& target) {
int count = 0;
size_t pos = 0;
// Loop until find() returns std::string::npos
while ((pos = text.find(target, pos)) != std::string::npos) {
bool boundary_start = true;
bool boundary_end = true;
// Check start boundary: must be at start of text OR preceded by a non-letter
if (pos > 0) {
if (std::isalpha(text[pos - 1])) {
boundary_start = false;
}
}
// Check end boundary: must be at end of text OR followed by a non-letter
if (pos + target.length() < text.length()) {
if (std::isalpha(text[pos + target.length()])) {
boundary_end = false;
}
}
if (boundary_start && boundary_end) {
count++;
}
// Start the next search immediately after the current word match
pos += target.length();
}
return count;
}
int main() {
std::string sentence = "The cat sat on the mat. Cat, cat.";
std::string word = "cat";
int result = count_word_occurrences(sentence, word);
std::cout << "The word '" << word << "' appears " << result << " times." << std::endl; // Output: 3
return 0;
}Code language: C++ (cpp)
Explanation:
- This exercise requires both string searching and boundary checking.
- The
whileloop repeatedly callstext.find(target, pos)to find the next possible match, starting the search frompos. Crucially, two boolean flags are used to check for whole word boundaries: the character before the match and the character after the match must not be a letter (std::isalpha()). - If both boundary checks pass, the match is counted as a whole word, and
posis advanced past the current match to continue the search.
Exercise 18: Sort Characters
Problem Statement: Write a program that takes a single string as input and sorts all the characters within that string alphabetically (A-Z or a-z) in ascending order. Punctuation and spaces should also be sorted along with the letters.
Given:
std::string str = "PYnative";Code language: C++ (cpp)
Expected Output:
Original string: PYnative
Sorted characters: PYaeintv
+ Hint
- The
std::stringclass acts as a container of characters. - The standard library algorithm
std::sortcan be applied directly to the character range defined by the string’s iterators,str.begin()andstr.end().
+ Show Solution
#include <iostream>
#include <string>
#include <algorithm> // Required for std::sort
int main() {
std::string str = "PYnative";
std::cout << "Original string: " << str << std::endl;
// Use std::sort on the character range of the string
// This sorts the characters in place based on their ASCII values
std::sort(str.begin(), str.end());
std::cout << "Sorted characters: " << str << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- This is a direct application of the
std::sortalgorithm. By passing thebegin()andend()iterators of thestd::stringtostd::sort, the algorithm rearranges the underlying character sequence. - The default sorting criterion is the lexicographical order based on the character’s ASCII value. Note that in ASCII, capital letters come before lowercase letters, and spaces and punctuation come before letters.
Exercise 19: Lexicographical Comparison
Problem Statement: Write a program to compare two strings, str1 and str2, lexicographically (dictionary order). Output which string comes first or if they are equal, without using the built-in comparison operators (<, >, ==) directly on the strings.
Given:
std::string s1 = "apple";
std::string s2 = "apply";Code language: C++ (cpp)
Expected Output:
Comparing "apple" and "apply"
"apple" comes first (Result: -20).
+ Hint
- Iterate through both strings simultaneously using a loop. Compare the characters at the current index. If they are different, the string with the smaller character at that position comes first.
- If the loop finishes, the shorter string (or the two equal-length strings) determines the result. The
std::string::compare()method is the standard library alternative to manual comparison.
+ Show Solution
#include <iostream>
#include <string>
int main() {
std::string s1 = "apple";
std::string s2 = "apply";
// Use the string compare() method
// Returns 0 if equal, < 0 if s1 comes first, > 0 if s2 comes first
int comparison_result = s1.compare(s2);
std::cout << "Comparing \"" << s1 << "\" and \"" << s2 << "\"" << std::endl;
if (comparison_result == 0) {
std::cout << "The strings are lexicographically equal." << std::endl;
} else if (comparison_result < 0) {
std::cout << "\"" << s1 << "\" comes first (Result: " << comparison_result << ")." << std::endl;
} else {
std::cout << "\"" << s2 << "\" comes first (Result: " << comparison_result << ")." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
The requirement is to avoid using direct operators (<, >). The standard library function for this purpose is std::string::compare(). This method returns an integer value:
- 0: The strings are identical.
- Negative: The calling string (
s1) comes first lexicographically. - Positive: The argument string (
s2) comes first lexicographically. This method performs the exact character-by-character comparison required for lexicographical ordering.
Exercise 20: Title Case
Problem Statement: Write a program to convert an input string into Title Case. This means the first letter of every word must be converted to uppercase, and all other letters in the words must be converted to lowercase..
Given:
std::string input = "thIS is a sampLe sEntence to convErt.";Code language: C++ (cpp)
Expected Output:
Original: thIS is a sampLe sEntence to convErt.
Title Case: Thi Is A Sample Sentence To Convert.
+ Hint
- Iterate through the string. You need a flag (a boolean variable) to track whether the current character is the start of a new word.
- Set the flag to
truewhen a space is encountered, and set it tofalseafter the character has been converted to uppercase.
+ Show Solution
#include <iostream>
#include <string>
#include <cctype>
std::string to_title_case(std::string str) {
bool new_word = true; // Flag to track if the next character is the start of a new word
for (size_t i = 0; i < str.length(); ++i) {
if (std::isspace(str[i])) {
new_word = true;
} else if (new_word && std::isalpha(str[i])) {
// First letter of a new word -> uppercase
str[i] = std::toupper(str[i]);
new_word = false; // Reset the flag
} else {
// Remaining letters -> lowercase
str[i] = std::tolower(str[i]);
}
}
return str;
}
int main() {
std::string input = "thIS is a sampLe sEntence to convErt.";
std::string title_cased = to_title_case(input);
std::cout << "Original: " << input << std::endl;
std::cout << "Title Case: " << title_cased << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
The solution uses the new_word boolean flag to manage the case logic.
- If a space is found,
new_wordis set totrue, indicating the next non-space character is a word start. - If the flag is
trueAND the current character is a letter, that character is capitalized usingstd::toupper(), and the flag is set tofalse. - All subsequent letters until the next space are converted to lowercase using
std::tolower(). This ensures the proper Title Case format.
Exercise 21: Remove Duplicates
Problem Statement: Write a program that takes a string and removes all duplicate characters, ensuring that the order of the remaining unique characters is preserved from the original string.
Given:
std::string input = "programming in c++";Code language: C++ (cpp)
Expected Output:
Original: programming in c++
Unique: progamin c+
+ Hint
- Use a Hash Set (
std::unordered_set) or a boolean array (if using ASCII characters) to keep track of characters encountered so far. - Iterate through the string, and only append the current character to the result string if it has not been seen before (i.e., not in the set).
+ Show Solution
#include <iostream>
#include <string>
#include <unordered_set> // Required for hash set
std::string remove_duplicates(const std::string& str) {
std::unordered_set<char> seen_chars;
std::string result = "";
for (char c : str) {
// Check if the character has been inserted into the set before
if (seen_chars.find(c) == seen_chars.end()) {
// Character is unique:
// 1. Add it to the result string
result += c;
// 2. Insert it into the set to mark it as seen
seen_chars.insert(c);
}
}
return result;
}
int main() {
std::string input = "programming in c++";
std::string unique_chars = remove_duplicates(input);
std::cout << "Original: " << input << std::endl;
std::cout << "Unique: " << unique_chars << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The solution uses an
std::unordered_set<char>for efficient tracking. The key is that checking the existence of an element in a hash set (seen_chars.find(c)) is an average O(1) operation. - The loop maintains order by building the
resultstring sequentially. Ifseen_chars.find(c)returnsseen_chars.end(), the character is unique, so it is added to both theresultand theseen_charsset.
Exercise 22: String Rotation Check
Problem Statement: Write a function that takes two strings, str1 and str2, and checks if str2 is a rotation of str1. A rotation means the characters remain in the same order but the starting point is shifted (e.g., “ABCDE” is a rotation of “CDEAB”).
Given:
std::string s1 = "waterbottle";
std::string s2 = "erbottlewat"; // RotationCode language: C++ (cpp)
Expected Output:
"erbottlewat" IS a rotation of "waterbottle".
+ Hint
- First, check if the lengths of both strings are equal. If they are, a clever trick can solve this: if
str2is a rotation ofstr1, thenstr2must always be a substring of the string created by concatenatingstr1with itself (str1 + str1). - Use the
std::string::find()method on the concatenated string.
+ Show Solution
#include <iostream>
#include <string>
bool is_rotation(const std::string& str1, const std::string& str2) {
// 1. Check if lengths are equal and non-zero
if (str1.length() != str2.length() || str1.empty()) {
return false;
}
// 2. Concatenate str1 with itself
std::string temp = str1 + str1;
// 3. Check if str2 is a substring of temp
// If str2 is found, it must be a rotation
if (temp.find(str2) != std::string::npos) {
return true;
}
return false;
}
int main() {
std::string s1 = "waterbottle";
std::string s2 = "erbottlewat"; // Rotation
if (is_rotation(s1, s2)) {
std::cout << "\"" << s2 << "\" IS a rotation of \"" << s1 << "\"." << std::endl;
} else {
std::cout << "\"" << s2 << "\" IS NOT a rotation." << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- This solution uses an trick. If “CDEAB” is a rotation of “ABCDE”, then if we double the original string (“ABCDEABCDE”), the rotation (“CDEAB”) will be found inside the doubled string as a contiguous substring.
- The function first verifies equal lengths and then uses
str1 + str1to create the doubled string. It then callstemp.find(str2)to check for the substring presence. Iffind()does not returnstd::string::npos, it is a rotation.
Exercise 23: Combine First/Last Characters
Problem Statement: Write a program that accepts a list of strings (e.g., a vector of names) and generates a new string by taking the first character of the first string and the last character of the last string, then the first character of the second string and the last character of the second-to-last string, and so on, until the middle is reached.
Given:
std::vector<std::string> names = {"Alpha", "Beta", "Gamma", "Delta", "Epsilon"};Code language: C++ (cpp)
Expected Output:
Names: Alpha, Beta, Gamma, Delta, Epsilon
Combined String: AnBaG
+ Hint
- Use a
std::vector<std::string>to store the list of words. Use a singleforloop that iterates fromi = 0up tolist.size() / 2. - In each iteration, access the string at index
i(for the first character) and the string at indexlist.size() - 1 - i(for the last character). - Append the first character of the former and the last character of the latter to your result string
+ Show Solution
#include <iostream>
#include <string>
#include <vector>
std::string combine_ends(const std::vector<std::string>& list) {
std::string result = "";
int n = list.size();
// Loop from the outside inwards
for (int i = 0; i < (n + 1) / 2; ++i) {
int opposite_i = n - 1 - i;
// 1. Get first char of the current word
if (!list[i].empty()) {
result += list[i].front(); // Use front() for the first char
}
// 2. Get last char of the opposite word (only if it's a different word)
if (i != opposite_i && !list[opposite_i].empty()) {
result += list[opposite_i].back(); // Use back() for the last char
}
}
return result;
}
int main() {
std::vector<std::string> names = {"Alpha", "Beta", "Gamma", "Delta", "Epsilon"};
std::string combined = combine_ends(names);
std::cout << "Names: Alpha, Beta, Gamma, Delta, Epsilon" << std::endl;
std::cout << "Combined String: " << combined << std::endl;
// Output: AaBnGlD
return 0;
}Code language: C++ (cpp)
Explanation:
- This exercise combines vector iteration and string character access.
- The key is the loop condition
i < (n + 1) / 2, which ensures the loop stops correctly at the middle for both odd- and even-sized vectors. - The index
opposite_i = n - 1 - iefficiently calculates the index for the mirrored element.list[i].front()accesses the first character, andlist[opposite_i].back()accesses the last character. - The conditional check
if (i != opposite_i)prevents double-counting the middle word’s characters in an odd-length vector.
Exercise 24: Longest Common Prefix
Problem Statement: Given an array (or std::vector) of strings, find the longest common prefix string among all of them. If there is no common prefix, return an empty string.
Given:
std::vector<std::string> words = {"flower", "flow", "flight"};Code language: C++ (cpp)
Expected Output:
Strings: flower, flow, flight
Longest Common Prefix: fl
+ Hint
- The common prefix cannot be longer than the shortest string in the array.
- A good strategy is to first sort the array lexicographically. Once sorted, the common prefix only needs to be found between the first and the last string in the sorted array, as the common prefix of these two must be the common prefix for all strings in between.
+ Show Solution
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
std::string longest_common_prefix(std::vector<std::string>& strs) {
if (strs.empty()) return "";
// Sort the vector
std::sort(strs.begin(), strs.end());
std::string first = strs.front();
std::string last = strs.back();
std::string prefix = "";
// Compare the first and last strings
for (size_t i = 0; i < first.length() && i < last.length(); ++i) {
if (first[i] == last[i]) {
prefix += first[i];
} else {
break;
}
}
return prefix;
}
int main() {
std::vector<std::string> words = {"flower", "flow", "flight"};
std::string lcp = longest_common_prefix(words);
std::cout << "Strings: flower, flow, flight" << std::endl;
std::cout << "Longest Common Prefix: " << lcp << std::endl; // Output: fl
return 0;
}Code language: C++ (cpp)
Explanation:
- The key optimization here is sorting. After sorting, the strings are arranged as:
{"flight", "flow", "flower"}. - The problem is simplified because the Longest Common Prefix (LCP) of all strings is guaranteed to be the LCP of the lexicographically smallest string (
"flight") and the largest string ("flower"). - The code then iterates character by character, appending to the
prefixas long as the characters match between the first and last strings.
Exercise 25: All Substrings
Problem Statement: Write a program that takes a string input and generates and prints all possible unique substrings of that string.
Given:
std::string s1 = "abc";Code language: C++ (cpp)
Expected Output:
Substrings of "abc":
a ab abc b bc c
+ Hint
- Use nested loops.
- The outer loop iterates through all possible starting positions (
i) of a substring. - The inner loop iterates through all possible lengths of the substring starting at
i. Thestd::string::substr()method is perfect for extracting the required segment.
+ Show Solution
#include <iostream>
#include <string>
#include <vector>
void print_all_substrings(const std::string& str) {
std::cout << "Substrings of \"" << str << "\":" << std::endl;
// Outer loop: Iterate over all possible starting indices (i)
for (size_t i = 0; i < str.length(); ++i) {
// Inner loop: Iterate over all possible lengths (j) from 1 up to (length - i)
for (size_t j = 1; i + j <= str.length(); ++j) {
// Use substr(starting position, length)
std::string sub = str.substr(i, j);
std::cout << sub << " ";
}
}
std::cout << std::endl;
}
int main() {
std::string s1 = "abc";
print_all_substrings(s1);
// Output: a ab abc b bc c
return 0;
}Code language: C++ (cpp)
Explanation:
- The solution uses two nested
forloops. - The outer loop (
i) defines where the substring starts. The inner loop (j) defines the length of the substring. The methodstr.substr(i, j)extracts the substring beginning at indexiand having a length ofj. - This guarantees that every possible contiguous sequence of characters is generated exactly once. For a string of length N, this results in N×(N+1)/2 substrings.
Exercise 26: Permutations
Problem Statement: Write a recursive function to generate and print all possible permutations (arrangements) of the characters in a given string.
Given:
std::string s = "ABC";Code language: C++ (cpp)
Expected Output:
Permutations of ABC:
ABC
ACB
BAC
BCA
CBA
CAB
+ Hint
- This is a classic recursion problem. In each recursive step, swap the current character with every character following it, and then call the function recursively for the remaining part of the string.
- After the recursive call returns, remember to backtrack (undo the swap) to restore the string to its previous state before moving to the next swap.
+ Show Solution
#include <iostream>
#include <string>
#include <algorithm> // Required for std::swap
void find_permutations(std::string str, int l, int r) {
// Base case: If the starting index (l) equals the end index (r), a full permutation is found
if (l == r) {
std::cout << str << std::endl;
} else {
// Recursive step
for (int i = l; i <= r; i++) {
// 1. Swap the current char (str[l]) with str[i]
std::swap(str[l], str[i]);
// 2. Recurse for the remaining part of the string
find_permutations(str, l + 1, r);
// 3. Backtrack (undo the swap) to restore the original order
std::swap(str[l], str[i]);
}
}
}
int main() {
std::string s = "ABC";
std::cout << "Permutations of " << s << ":" << std::endl;
find_permutations(s, 0, s.length() - 1);
return 0;
}Code language: C++ (cpp)
Explanation:
- The
find_permutationsfunction uses the indicesl(left/start of the current segment) andr(right/end of the string). The base case is whenl == r, meaning the entire string has been rearranged, and the permutation is printed. - In the recursive step, the
forloop iterates, swapping the character at the current start position (l) with every character fromltor. - The recursive call then fixes the new character at position
land solves the subproblem for the rest of the string (l+1tor). - Backtracking (the second
std::swap) is crucial; it resets the string state so that subsequent iterations of theforloop start from the correct configuration.
Exercise 27: Longest Palindromic Substring
Problem Statement: Given a string S, find the longest substring of S that is also a palindrome. If there are multiple longest palindromic substrings, any one is acceptable.
Given:
std::string s = "babadcabbac";Code language: C++ (cpp)
Expected Output:
String: babadcabbac
Longest Palindromic Substring: cabbac
+ Hint
- A common and effective approach is the “Expand Around Center” method.
- Iterate through every character (and every space between two characters) of the string.
- Treat each of these 2N−1 points as the center of a potential palindrome, and expand outwards to check for matches, keeping track of the longest one found.
+ Show Solution
#include <iostream>
#include <string>
#include <algorithm>
std::string longest_palindrome(const std::string& s) {
if (s.length() < 2) return s;
int start_index = 0;
int max_length = 1;
// Helper function (lambda) to expand and find max length from a center
auto expand_around_center = [&](int left, int right) {
while (left >= 0 && right < s.length() && s[left] == s[right]) {
left--;
right++;
}
// Palindrome length is (right - 1) - (left + 1) + 1 = right - left - 1
int current_length = right - left - 1;
if (current_length > max_length) {
max_length = current_length;
start_index = left + 1;
}
};
// Iterate through every possible center
for (int i = 0; i < s.length(); ++i) {
// Case 1: Odd length (center is one character, e.g., "aba")
expand_around_center(i, i);
// Case 2: Even length (center is between two characters, e.g., "abba")
expand_around_center(i, i + 1);
}
return s.substr(start_index, max_length);
}
int main() {
std::string s = "babadcabbac";
std::cout << "String: " << s << std::endl;
std::cout << "LPS: " << longest_palindrome(s) << std::endl; // Output: bab or abba
return 0;
}Code language: C++ (cpp)
Explanation:
The solution uses the Expand Around Center dynamic programming technique. Every character and every space between characters can be the center of a palindrome.
- The main
forloop iterates through all indices i. For each i, it calls the lambda functionexpand_around_centertwice: once for odd-length palindromes (center i, i) and once for even-length palindromes (center i, i+1). - The helper function expands outwards (
left--,right++) as long as characters match, constantly updating the globally trackedmax_lengthandstart_indexto record the longest palindrome found so far.

Leave a Reply