Home >Backend Development >C++ >How to Remove Leading, Trailing, and Extra Spaces from a String in C ?
Removing Leading and Trailing Spaces from a String in C
String manipulation in C often involves removing unnecessary spaces from strings. This can be particularly useful for tasks such as data cleaning or text processing.
Removing Leading and Trailing Spaces
To remove leading and trailing spaces, one can employ the find_first_not_of and find_last_not_of methods. These functions find the first and last non-whitespace characters in a string, respectively. Using these values, one can obtain the substring that contains the non-whitespace characters:
std::string trim(const std::string& str, const std::string& whitespace = " \t") { const auto strBegin = str.find_first_not_of(whitespace); if (strBegin == std::string::npos) return ""; // no content const auto strEnd = str.find_last_not_of(whitespace); const auto strRange = strEnd - strBegin + 1; return str.substr(strBegin, strRange); }
Removing Extra Spaces Between Words
To remove extra spaces between words, an additional step is required. This can be achieved using the find_first_of, find_last_of, find_first_not_of, and find_last_not_of methods along with substr to replace the extra spaces with a single space:
std::string reduce(const std::string& str, const std::string& fill = " ", const std::string& whitespace = " \t") { // trim first auto result = trim(str, whitespace); // replace sub ranges auto beginSpace = result.find_first_of(whitespace); while (beginSpace != std::string::npos) { const auto endSpace = result.find_first_not_of(whitespace, beginSpace); const auto range = endSpace - beginSpace; result.replace(beginSpace, range, fill); const auto newStart = beginSpace + fill.length(); beginSpace = result.find_first_of(whitespace, newStart); } return result; }
Example Usage
The following code snippet demonstrates the usage of these functions:
const std::string foo = " too much\t \tspace\t\t\t "; const std::string bar = "one\ntwo"; std::cout << "[" << trim(foo) << "]" << std::endl; std::cout << "[" << reduce(foo) << "]" << std::endl; std::cout << "[" << reduce(foo, "-") << "]" << std::endl; std::cout << "[" << trim(bar) << "]" << std::endl;
Output:
[too much space] [too much space] [too-much-space] [one two]
The above is the detailed content of How to Remove Leading, Trailing, and Extra Spaces from a String in C ?. For more information, please follow other related articles on the PHP Chinese website!