Mastering C++ String Manipulation: A Step-by-Step Guide
Example 1: Removing Non-Alphabetic Characters from a C++ String Object
Imagine having a string object filled with unwanted characters, and you need to extract only the alphabets. With this example, you’ll learn how to remove all non-alphabetic characters from a string object.
#include <iostream>
#include <cctype>
int main() {
std::string str;
std::cout << "Enter a string: ";
std::getline(std::cin, str);
std::string result;
for (char c : str) {
if (std::isalpha(c)) {
result += c;
}
}
std::cout << "Output: " << result << std::endl;
return 0;
}
The program prompts the user to input a string, and then it uses a for loop to iterate through each character. If the character is an alphabet, it’s kept; otherwise, it’s removed. The result is a string containing only alphabets.
Output:
- Enter a string: Hello, World!
- Output: HelloWorld
Example 2: Removing Non-Alphabetic Characters from a C-Style String
But what if you’re working with a C-style string instead of a string object? This example shows you how to remove non-alphabetic characters from a C-style string.
#include <iostream>
#include <cctype>
int main() {
char str[100];
std::cout << "Enter a string: ";
std::cin.getline(str, 100);
int len = strlen(str);
int j = 0;
for (int i = 0; i < len; i++) {
if (isalpha(str[i])) {
str[j++] = str[i];
}
}
str[j] = '\0';
std::cout << "Output: " << str << std::endl;
return 0;
}
The program follows a similar approach, using a for loop to iterate through each character. However, this time, it uses the isalpha()
function to check if the character is an alphabet. If it’s not, it’s removed from the string.
Output:
- Enter a string: Hello, World!
- Output: HelloWorld
Taking Your String Manipulation Skills Further
Want to explore more advanced string manipulation techniques? Check out our article on C++ Program to Find the Number of Vowels, Consonants, Digits, and White Spaces in a String. It’s packed with valuable insights and examples to help you master C++ strings.