- Unnecessary spaces at the starting, end, and even in the center
- Trying to figure out how many characters there are in a string
- Attempting to organize a set of strings
- When two strings are compared
- Adding a URL to a site
If our C++ code encounters spaces while performing any of these previous operations, we will receive unexpected outcomes, such as wrong character counts, incorrectly sorted lists, inaccurate string comparisons, and broken URLs. By default, these are considered whitespace characters, i.e., “\n”, “\t”, “ ”, “\v”, “\r”, “f”.
It is sometimes important to remove space from strings in programming to avoid unexpected outcomes. Learn how to remove spaces from strings and how to cope with additional spaces with this article.
Example 1: Using the::isSpace Method To Remove Whitespaces From the String in C++
To extract whitespace characters from std::strings, the common approach is to utilize the std::remove if method. The std::remove_if algorithm does not effectively eliminate characters from the string but rather moves all the characters with the non-whitespaces to the front and produces an iterator referring to the end. The method std::remove_if requires a predicate that decides which characters to erase from the string.
The isSpace() method is the one that is specified in the cctype header and searches for whitespace characters categorized by the installed C locale.
The following example starts from the main function. The standard string class’s string declaration is defined in the main method. The string variable is defined as “str” and is initialized with the string containing the whitespace characters. To remove whitespaces from the string, we used the normal erase procedure.
We have used the std::remove_if method. In the std::remove_if method, we have passed the “::isSpace” function in a search for a whitespace character in a given string. The string after removing the whitespaces will be printed on the following screen:
#include <string>
#include <cctype>
#include <algorithm>
int main()
{
std::string str = "c \n\nplusplus";
str.erase(std::remove_if(str.begin(), str.end(), ::isspace), str.end());
std::cout<< "String:"<< str<<"\n";
return 0;
}
As you can see, no whitespace character is found in the following displayed string:
Example 2: Using the std::isSpace Method To Remove Whitespaces From the String in C++
In this example, we use the standard bind method to remove the whitespace from the string by calling the std::isSpace function. Instead of depending on the C locale’s classification of whitespace characters, we can use std::isSpace represented in the header locale, where the ctype aspect of the specified locale classifies the whitespace characters.
Binding a function with placeholders allows you to change the position and quantity of values that the function will utilize, altering the function based on the desired outcome.
The string is defined as “str_n” in the main and is initialized with the string word having whitespace characters between them. Here, we have invoked the erase method for the string “str_n” where two functions are used std:: remove_if and the std::bind. Note that we have used std::isSpace in the bind function for finding whitespaces in the string; then, the erase method will remove whitespace from the string and return a new outcome string.
#include <string>
#include <algorithm>
#include <locale>
#include <functional>
int main()
{
std::string str_n = "White \n\nspaces";
str_n.erase(std::remove_if(str_n.begin(),
str_n.end(),
std::bind(std::isspace,
std::placeholders::_1,
std::locale::classic()
)),
str_n.end());
std::cout<< "String:"<<str_n<<"\n";
return 0;
}
Upon compiling the previous program, the shell displays the non-whitespace characters.
Example 3: Using the Unary Method To Remove Whitespaces From the String in C++
Instead of using::isspace or std::isSpace, we may create a custom condition that returns true if the character is a whitespace character or else false. We have created our unary method to remove whitespace characters from the string.
We have created a unary method “MyFunction” of data type bool. The function has passed with the argument of the unsigned char variable “MyChar”. Inside the function, we have a return condition that returns the specified whitespace character if found in the string.
Then, we have the main function where the string is generated as “MyString” and contains the string characters with whitespace characters. The erase method is used hereafter in the string declaration where remove_if and function “MyFunction” is called erasing the whitespace characters.
#include <string>
#include <algorithm>
bool MyFunction(unsigned char MyChar) {
return (MyChar == ' ' || MyChar == '\n' || MyChar == '\r' ||
MyChar == '\t' || MyChar == '\v' || MyChar == '\f');
}
int main()
{
std::string MyString = "Mc \n\nDonald";
MyString.erase(std::remove_if(MyString.begin(), MyString.end(), MyFunction), MyString.end());
std::cout<< "String:" <<MyString<<"\n";
return 0;
}
The resultant string has all non-whitespace characters shown in the following shell screen:
Example 5: Using the Regex Method To Remove Whitespaces From the String in C++
The regex replace() method replaces a regular expression pattern with a string containing whitespace characters. Let’s discuss it with the example demonstration.
The C++ program includes a regex file in the header section to access the regex_replace function in the program. The int main is defined, which has an integral string representation with the whitespace characters in a string variable “StringIs”. Then, we have called the regex function in a stranded regex representation and passed the string variable “StringIs” with the “+” operator. The regex_replace function is called over the variable string “StringIs” for erasing the whitespaces or whitespace characters from the given string:
#include <string>
#include <regex>
int main()
{
std::string StringIS = "1 \n\n2 \n\n3 \n\n4 \n\n5 ";
std::regex regx("\\StringIS+");
StringIS = std::regex_replace(StringIS, regx, "");
std::cout<<StringIS<<"\n";
return 0;
}
The regex replace removes the whitespace characters from the integer string, which is printed in the command shell of Ubuntu.
Conclusion
Thus, we can remove whitespace characters from the string in C++ through various methods discussed in this article. We have all the demonstrations of these examples with the resultant outcome of the program. You have a sufficient number of methods for replacing or removing white spaces from C++ strings. Choose any methods that attract you while also being appropriate for the situation.