「労働者が自分の仕事をうまくやりたいなら、まず自分の道具を研ぎ澄まさなければなりません。」 - 孔子、「論語。陸霊公」
表紙 > プログラミング > C++ で文字列から先頭、末尾、余分なスペースを削除する方法

C++ で文字列から先頭、末尾、余分なスペースを削除する方法

2024 年 11 月 22 日に公開
ブラウズ:429

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

単語間の余分なスペースを削除する

単語間の余分なスペースを削除するには、追加の手順が必要です。これは、find_first_of、find_last_of、find_first_not_of、および find_last_not_of メソッドを substr とともに使用して、余分なスペースを単一のスペースに置き換えることで実現できます:

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