2011-07-22 13 views
0

"Name_1"と "1535"のような変数があります。文字列に文字または数字が含まれているかどうかを確認する方法C++およびC#

変数値が "1535"(数字)か "Name_1"(名前)かどうかを判断するには、C++またはC#のライブラリ関数が必要です。

利用可能な機能を教えてください。

+0

あなたは数字上の任意の範囲を持っていますか? "-2"は発生する可能性のある値ですか? "3.1415"ですか? 「3E-4」ですか? –

+0

@Rahul、あなたが誰かの答えを正しいと判断した場合は、回答としてマークしてください。あなたの受け入れ率を0%と見なすと、他の人があなたの質問に答えることを嫌がるかもしれません。 – Ajay

答えて

1

"文字" として任意の非整数の文字列を考えてしても大丈夫であると仮定すると:boost::lexical_castはこのために便利になり、C++では

String variable = "1234"; 
Integer dummyresult 
if Int32.TryParse(variable,dummyresult) 
{ 
    // variable is numeric 
} 
else 
{ 
    // variable is not numeric 
} 
1
string s = "1235"; 

Console.WriteLine("String is numeric: " + Regex.IsMatch(s, "^[0-9]+$")); 
1

Int32.TryParse

#include <boost/lexical_cast.hpp> 
#include <iostream> 

bool IsNumber(const char *s) { 
    using boost::lexical_cast; 

    try { 
    boost::lexical_cast<int>(s); 
    return true; 
    } catch (std::bad_cast&) { 
    return false; 
    } 
} 

int main(int ac, char **av) { 
    std::cout << av[1] << ": " << std::boolalpha << IsNumber(av[1]) << "\n"; 
} 


EDIT:ブーストはあなたに利用できない場合は、これを試してみてください。

bool IsNumber2(const char *s) { 

    std::istringstream stream(s); 
    stream.unsetf(std::ios::skipws); 

    int i; 
    if((stream >> i) && stream.eof()) 
    return true; 
    return false; 
} 
関連する問題