C++ Function to Remove Spaces from a String
To remove the spaces from a given string and return the resultant string, you can iterate through each character of the input string. If the character is not a space, you append it to a new string. Finally, you return the new string without spaces.
Here's the implementation of the 'no_space' function:
#include <string>
std::string no_space(const std::string& x) {
std::string result = '';
for (char c : x) {
if (c != ' ') {
result += c;
}
}
return result;
}
In the function, we initialize an empty string 'result' to store the final result. We iterate through each character 'c' in the input string 'x'. If 'c' is not a space, we append it to 'result' using the '+=' operator. Finally, we return the 'result' string without spaces.
You can call the 'no_space' function with the input string to remove the spaces and obtain the resultant string.
I hope this helps! If you have any further questions, feel free to ask.
原文地址: https://gggwd.com/t/topic/Dcg 著作权归作者所有。请勿转载和采集!