c++ remove whitespace from string and keep the same size
To remove whitespace from a string in C++ while keeping the same size, you can use the std::remove_if
function from the <algorithm>
header along with a lambda function. Here are the steps to achieve this:
Include the necessary headers:
cpp #include <algorithm> #include <string>
Define a lambda function that checks if a character is whitespace:
cpp auto isWhitespace = [](char c) { return std::isspace(static_cast<unsigned char>(c)); };
Create a string variable and assign the input string to it:
cpp std::string inputString = "This is a string with whitespace.";
Use the
std::remove_if
function to remove the whitespace from the string:cpp inputString.erase(std::remove_if(inputString.begin(), inputString.end(), isWhitespace), inputString.end());
Let's break down the std::remove_if
function call:
inputString.begin()
andinputString.end()
specify the range of characters to process, which is the entire string.isWhitespace
is the unary predicate function that determines if a character is whitespace.std::remove_if
moves all the non-whitespace characters to the beginning of the string and returns an iterator pointing to the first element after the removed characters.inputString.erase()
erases the characters from the iterator returned bystd::remove_if
to the end of the string, effectively removing the whitespace.
After these steps, the inputString
will contain the original string without any whitespace, and its size will remain the same.
Here's the complete code:
#include <algorithm>
#include <cctype>
#include <string>
int main() {
auto isWhitespace = [](char c) { return std::isspace(static_cast<unsigned char>(c)); };
std::string inputString = "This is a string with whitespace.";
inputString.erase(std::remove_if(inputString.begin(), inputString.end(), isWhitespace), inputString.end());
return 0;
}
Please note that the std::isspace
function from the <cctype>
header is used to check if a character is whitespace. This function handles not only the space character (' '), but also other whitespace characters such as tabs and newlines.