3

これらのケースをチェックする方法はありますか? または、文字列内の各文字を解析し、それが小文字 (文字) であり、数字/文字であるかどうかを確認する必要がありますか?

4

6 に答える 6

5

islower()isalnum()を使用して、各文字の条件を確認できます。これを行うための文字列レベルの関数はないため、独自に作成する必要があります。

于 2012-07-03T00:32:52.803 に答える
3

「C」ロケールが受け入れ可能である(またはの別の文字セットに交換するcriteria)と仮定して、次を使用します。find_first_not_of()

#include <string>

bool testString(const std::string& str)
{
      std::string criteria("abcdefghijklmnopqrstuvwxyz0123456789");
      return (std::string::npos == str.find_first_not_of(criteria);
}
于 2012-07-03T00:42:17.383 に答える
3

あまり知られていませんが、実際にはロケールに文字列全体の特性を一度に判別する機能があります。具体的にはctype、ロケールのファセットには、指定されたマスク (英字、数字、英数字、小文字、大文字、句読点、スペース、16 進数など) に適合する最初の文字、または適合しない最初の文字をスキャンするscan_isおよびがあります。scan_notそれぞれフィットします。それ以外は、 のように機能し、std::find_if失敗を通知するために「終了」として渡したものを返します。それ以外の場合は、要求したものに適合しない文字列内の最初の項目へのポインターを返します。

簡単なサンプルを次に示します。

#include <locale>
#include <iostream>
#include <iomanip>

int main() {

    std::string inputs[] = { 
        "alllower",
        "1234",
        "lower132",
        "including a space"
    };

    // We'll use the "classic" (C) locale, but this works with any
    std::locale loc(std::locale::classic());

    // A mask specifying the characters to search for:          
    std::ctype_base::mask m = std::ctype_base::lower | std::ctype_base::digit;

    for (int i=0; i<4; i++) {
        char const *pos;
        char const *b = &*inputs[i].begin();
        char const *e = &*inputs[i].end();

        std::cout << "Input: " << std::setw(20) << inputs[i] << ":\t";

        // finally, call the actual function:
        if ((pos=std::use_facet<std::ctype<char> >(loc).scan_not(m, b, e)) == e)
            std::cout << "All characters match mask\n";
        else
            std::cout << "First non-matching character = \"" << *pos << "\"\n";
    }
    return 0;
}

ただし、ほとんどの人は使用することを好むと思いstd::find_ifます-使用方法はほぼ同じです、より多くの状況に非常に簡単に一般化できます. これは適用範囲がはるかに狭いですが、使いやすいとは言えません (ただし、大量のテキストをスキャンしている場合は、少なくとも少しは高速になると思います)。

于 2012-07-03T04:20:24.973 に答える
0

tolower & strcmp を使用して、original_string と tolowered string を比較することができます。また、文字ごとに個別に数値を計算します。

(または) 以下のように、文字ごとに両方を実行します。

#include <algorithm>

static inline bool is_not_alphanum_lower(char c)
{
    return (!isalnum(c) || !islower(c));
}

bool string_is_valid(const std::string &str)
{
    return find_if(str.begin(), str.end(), is_not_alphanum_lower) == str.end();
}

次の情報を使用しました: 文字列に英数字(またはスペース)のみが含まれているかどうかを判断します

于 2012-07-03T00:46:05.353 に答える
-1

文字列にASCIIでエンコードされたテキストが含まれていて、(私のように)独自の関数を記述したい場合は、次のように使用できます。

bool is_lower_alphanumeric(const string& txt)
{
  for(char c : txt)
  {
    if (!((c >= '0' and c <= '9') or (c >= 'a' and c <= 'z'))) return false;
  }
  return true;
}
于 2012-07-03T01:03:05.707 に答える