これらのケースをチェックする方法はありますか? または、文字列内の各文字を解析し、それが小文字 (文字) であり、数字/文字であるかどうかを確認する必要がありますか?
6 に答える
「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);
}
あまり知られていませんが、実際にはロケールには文字列全体の特性を一度に判別する機能があります。具体的には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
ます-使用方法はほぼ同じですが、より多くの状況に非常に簡単に一般化できます. これは適用範囲がはるかに狭いですが、使いやすいとは言えません (ただし、大量のテキストをスキャンしている場合は、少なくとも少しは高速になると思います)。
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();
}
次の情報を使用しました: 文字列に英数字(またはスペース)のみが含まれているかどうかを判断します
文字列に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;
}