Home  >  Article  >  Backend Development  >  How can I trim and reduce strings in C ?

How can I trim and reduce strings in C ?

DDD
DDDOriginal
2024-11-13 11:56:02209browse

How can I trim and reduce strings in C  ?

Trimming and Reducing Strings in C

Trimming and reducing strings are common operations in programming. Trimming refers to removing leading and trailing whitespace characters from a string, while reducing involves replacing consecutive whitespace characters with a single predefined character or string.

Trimming Strings

To trim a string in C , you can use the find_first_not_of and find_last_not_of methods to identify the first and last non-whitespace characters. The code below illustrates this approach:

#include <string>

std::string trim(const std::string& str) {
    const auto strBegin = str.find_first_not_of(" \t");
    if (strBegin == std::string::npos)
        return ""; // no content

    const auto strEnd = str.find_last_not_of(" \t");
    const auto strRange = strEnd - strBegin + 1;

    return str.substr(strBegin, strRange);
}

Reducing Strings

Reducing a string involves replacing consecutive whitespace characters with a predefined character or string. Here's a function that performs this operation:

std::string reduce(const std::string& str, const std::string& fill = " ", const std::string& whitespace = " \t") {
    // trim first
    auto result = trim(str);

    // 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

Here's an example demonstrating the usage of the trim and reduce 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 can I trim and reduce strings in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn