1

さて、私は文字列が空であるか空白だけであるかを確認する方法についてStackOverflowを検索しました。ただし、ANSI文字列でのみ機能します。どうすればそれを動作させることができwstringますか?

コードは次のとおりです。

#include <string>
using namespace std;

//! Checks if a string is empty or is whitespace.
bool IsEmptyOrSpace(const string& str) {
    string::const_iterator it = str.begin();

    do {
        if (it == str.end())
            return true;
    } while (*it >= 0 && *it <= 0x7f && isspace(*(it++)));
    // One of these conditions will be optimized away by the compiler.
    // Which one depends on whether the characters are signed or not.

    return false;
}

私の最初の考えはに変更isspace(*(it++))することでしiswspace(*(it++))たが、その前の2つの条件はASCIIでのみ機能しますよね?これが私がこれまでに関数をwstring'sに適応させようとしてきたことです:

bool IsEmptyOrSpaceW(const wstring& str) {
    String::const_iterator it = str.begin();

    do {
        if (it == str.end())
            return true;
    } while (*it >= 0 && *it <= 0x7f && iswspace(*(it++)));
    // One of these conditions will be optimized away by the compiler.
    // Which one depends on whether the characters are signed or not.

        // Do I need to change "*it >= 0 && *it <= 0x7f" to something else?

    return false;
}

私のアプローチは正しいに近いですか?IsEmptyOrSpace()いずれにせよ、この関数のUnicodeバージョンを実装するにはどうすればよいですか?

編集: さて、あなたがテストがそこにある理由を知る必要があるならば*it >= 0 && *it <= 0x7f、私は知らないので、私はあなたに言うことができません。この質問への回答から関数のコードを取得しました:C ++は、文字列がスペースかnullか を確認します。最初から始めましょう。一般に、awstringが空か空白かを確認するにはどうすればよいですか?

4

2 に答える 2

4

しかし、その前の2つの条件は、ASCIIでのみ機能しますよね?

それは正しい。それらは、値が次の前提条件に準拠していることを確認しますisspace:引数「unsigned charまたはEOFの値を持っている必要があります」。厳密に言えば、必要なのはチェックだけです。これは、署名*it >= 0されていない場合は最適化する必要があります。charまたは、コメントに記載されているように、値をに変換することもできますunsigned

iswspaceそのような前提条件はないので、ワイドバージョンからこれらのチェックを削除するだけです。

bool IsEmptyOrSpaceW(const wstring& str) {
    wstring::const_iterator it = str.begin();

    do {
        if (it == str.end())
            return true;
    } while (iswspace(*(it++)));

    return false;
}

スタイルの問題として、パラメータタイプを示すような奇妙な疣贅を追加する必要はありません。これは、さまざまなパラメータタイプWでオーバーロードできるためです。IsEmptyOrSpace

于 2012-11-14T12:04:04.120 に答える
0
bool IsEmptyOrSpaceW(const wstring& str) {
  return str.length() == (size_t)std::count(str.begin(), str.end(), L' ');
}

また

// this code works for string and wstring
    template <typename CharType>
    bool IsEmptyOrSpace(const std::basic_string<CharType>& str)  {
      return str.length() == (size_t)std::count(str.begin(), str.end(), CharType(32));
    }

実際には、タブ文字などの他の種類の空白があり、このコードがそれらの空白文字を処理するかどうかについては確信が持てません。

これらすべての空白文字を処理する場合、isspace関数がfalseを返す最初のシンボルを見つけることができます

template <typename CharType>
bool IsEmptyOrSpace(const std::basic_string<CharType>& str)  {
  return str.end() == std::find_if(str.begin(), str.end(), 
          std::not1(std::ptr_fun((int(*)(int))isspace)));
}
于 2012-11-14T12:24:34.983 に答える