"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > C++의 문자열에서 선행, 후행 및 추가 공백을 제거하는 방법은 무엇입니까?

C++의 문자열에서 선행, 후행 및 추가 공백을 제거하는 방법은 무엇입니까?

2024년 11월 22일에 게시됨
검색:720

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

C의 문자열에서 선행 및 후행 공백 제거

C의 문자열 조작에는 문자열에서 불필요한 공백을 제거하는 작업이 포함되는 경우가 많습니다. 이는 데이터 정리 또는 텍스트 처리와 같은 작업에 특히 유용할 수 있습니다.

선행 및 후행 공백 제거

선행 및 후행 공백을 제거하려면 find_first_not_of를 사용할 수 있습니다. 및 find_last_not_of 메소드. 이 함수는 각각 문자열에서 공백이 아닌 첫 번째 문자와 마지막 문자를 찾습니다. 이러한 값을 사용하면 공백이 아닌 문자를 포함하는 하위 문자열을 얻을 수 있습니다.

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);
}

단어 사이의 추가 공백 제거

단어 사이의 추가 공백을 제거하려면 추가 단계가 필요합니다. 이는 추가 공백을 단일 공백으로 대체하기 위해 substr과 함께 find_first_of, find_last_of, find_first_not_of 및 find_last_not_of 메소드를 사용하여 달성할 수 있습니다:

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;
}

사용 예

다음 코드 조각은 이러한 함수의 사용을 보여줍니다.

const std::string foo = "    too much\t   \tspace\t\t\t  ";
const std::string bar = "one\ntwo";

std::cout 

출력:

[too much               space]
[too much space]
[too-much-space]
[one
two]
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3