[英]How to check if a string contains characters or numbers C++ and C#
我有可能的变量值如下“Name_1”和“1535”。
我想要一个库 function 在 C++ 或 C# 来确定变量值是“1535”(它是数字)还是“isName_1”)
让我知道有哪些可用功能?
假设可以将任何非整数字符串视为“字符”:
String variable = "1234";
Integer dummyresult
if Int32.TryParse(variable,dummyresult)
{
// variable is numeric
}
else
{
// variable is not numeric
}
string s = "1235";
Console.WriteLine("String is numeric: " + Regex.IsMatch(s, "^[0-9]+$"));
在 C++ 中, boost::lexical_cast派上用场了:
#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";
}
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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.