私はそれを言おうとしている
if(string.at(i) != 0-9){
b= true;
}
value != 0 && value != 1 ...などと入力せずにこれを言う方法はありますか? また、これが存在し可能であり、Java で異なる場合は、それも役立つと思います。
いつもお世話になっている方々、ありがとうございます。
私はそれを言おうとしている
if(string.at(i) != 0-9){
b= true;
}
value != 0 && value != 1 ...などと入力せずにこれを言う方法はありますか? また、これが存在し可能であり、Java で異なる場合は、それも役立つと思います。
いつもお世話になっている方々、ありがとうございます。
C++:
#include <cctype>
using namespace std;
...
if (!isdigit(str[i]))
// or
if (str[i] < '0' || str[i] > '9')
ジャワ:
if (!Character.isDigit(str.charAt(i)))
と言うstring[i] < 0 || string[i] > 9
。
(ゼロを表す数字の文字0
) ではなく、実際に (値) を意味していることを確認してください。'0'
後者の場合(コメントで提案しているように)、必要ですstring[i] < '0' || string[i] > '9'
。(数値は、どのテキスト エンコーディングでも連続して順序付けられることが保証されているため、これはどのプラットフォームでも機能します。)
アドホックソリューションの方が使いやすいので、使用するのは不器用ですが、標準ライブラリは実際にはこれを直接サポートしています。
#include <locale>
#include <iostream>
#include <iomanip>
int main() {
char *inputs[] = {
"0983",
"124test"
};
std::locale loc(std::locale::classic());
std::ctype_base::mask m = std::ctype_base::digit;
for (int i=0; i<2; i++) {
char const *b = inputs[i];
char const *e = b + strlen(b);
std::cout << "Input: " << std::setw(10) << inputs[i] << ":\t";
if (std::use_facet<std::ctype<char> >(loc).scan_not(m, b, e) == e)
std::cout << "All Digits\n";
else
std::cout << "Non digit\n";
}
return 0;
}
C ++ 11を使用している場合std::all_of
は、ほぼ間違いなく使いやすいです。
#include <string>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <ctype.h>
int main() {
std::string inputs[] = {
"0983",
"124test"
};
std::cout << std::boolalpha;
for (int i=0; i<2; i++)
std::cout << std::setw(10) << inputs[i] << "\tAll digits?: "
<< std::all_of(inputs[i].begin(), inputs[i].end(), ::isdigit) << "\n";
return 0;
}
文字列が「0983」の場合は true にしたいのですが、「124Test」の場合は false のままにしておきます。
そうは言っても、文字列の最後まですべての文字をチェックするのではなく、文字が数字ではないかどうかをチェックしてから false を返すというアプローチになります。
bool b = true;
for(int i = 0; i < string.size(); i++)
{
if(string.at(i) < '0' || string.at(i) > '9')
{
b = false;
break;
}
}
C++の回答については、この質問を見てください。これは、非常によく似た問題をすでに解決しており、状況に非常に簡単に適応できます。
Javaに関しては、これを行うことができます:
public boolean isInteger(String s) {
return s.matches("^[0-9]+$");
}
要件に合わせて正規表現を変更できます。例: "^[4-8]+$"
.
注:String.matches
は最適ではありません。チェックを頻繁に実行する必要がある場合は、代わりにコンパイル済みパターンを使用してください。
static final Pattern DIGITS = Pattern.compile("^[0-9]+$");
public void isInteger(String s) {
return DIGITS.matcher(s).find();
}
コレクション メンバーシップを使用できます。
!boost::empty(boost::find<boost::return_found_end>("0123456789", string.at(i)))