"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Remove Leading, Trailing, and Extra Spaces from a String in C++?

How to Remove Leading, Trailing, and Extra Spaces from a String in C++?

Published on 2024-11-22
Browse:453

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 

Output:

[too much               space]
[too much space]
[too-much-space]
[one
two]
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3