how to remove spaces from a string
To remove spaces from a string in C++, you can follow these steps:
- Define a string variable to store the input string.
- Use the
std::getline()
function to read the input string from the user. - Create a new string variable to store the modified string without spaces. Initialize it as an empty string.
- Use a loop to iterate through each character in the input string.
- Inside the loop, check if the current character is a space using the
std::isspace()
function from the<cctype>
library. - If the current character is not a space, append it to the modified string using the
+=
operator. - After the loop, the modified string will contain the original string without any spaces.
Here is an example code snippet that demonstrates the above steps:
#include <iostream>
#include <cctype>
int main() {
std::string inputString;
std::cout << "Enter a string: ";
std::getline(std::cin, inputString);
std::string modifiedString;
for (char c : inputString) {
if (!std::isspace(c)) {
modifiedString += c;
}
}
std::cout << "Modified string: " << modifiedString << std::endl;
return 0;
}
In this example, the std::getline()
function is used to read the input string from the user. The loop iterates through each character in the input string, and if the character is not a space, it is appended to the modifiedString
variable. Finally, the modified string is printed to the console.
Note: The <cctype>
library is included to use the std::isspace()
function, which checks if a character is a space.