如何检测字符串是否以数字开头? [英] How to detect if a string begins with a number?

查看:113
本文介绍了如何检测字符串是否以数字开头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了检测字符串是一个数字,通常会提出这个:



In order to detect that a string is a number it is usually propossed this:

bool isParam(string line)
{
    char* p;
    strtol(line.c_str(), &p, 10);
    return *p == 0;
}





不幸的是我*如果里面没有数字,p指向第一个字符,那就是没有0


我如何使用strtol()?



我的尝试:



然后我尝试了这个似乎有效,除非有人从点开始写小数:





Unfortunately for me *p points to first character if no number is inside, that is no 0

How I have to use the strtol()?

What I have tried:

Then I tried this that seems to work unless somebody writes decimals beginning by a point:

bool isNumber(string str1) 
{ 	
    char p = str1.c_str()[0]; return (p >= '0' && p <= '9'); 
}





Richard MacCutchan发布后,这对我有用:



After Richard MacCutchan post this worked for me:

bool isnumber(string str1) { return (isdigit(str1.c_str()[0])>0);}

推荐答案

研究C库函数,你会发现 isdigit()
Study the C library functions, and you will find isdigit().


如果你需要检测浮点值,然后使用 strtod [ ^ ](之后检查 str_end的值参数)。
If you need to detect also floating point values, then use strtod[^] (and afterwards check the value of the str_end parameter).


因为一个未知的原因,我在字符-96''上使用isdigit()时出现了断言错误,所以我建议使用:

Because an unknown reason, I had an Assertion error when using isdigit() on character -96 ' ', so I should recommend using:
if (line[0] >= '0' && line[0] <= '9')



而不是isdigit()



这是使用的函数(行[]有制表符) :


instead of isdigit()

Here is the function used (the line[] has tabulators):

//char line[]="N 2	32.1dC	28.7dC	25.2dC	20.7dC	19.6dC	18.5dC	74 %	67 %	52 %	4 kph	2 kph	0 kph";
double string_to_double2(char *line, int num)
{
	int i1 = 0, max = (int) strlen(line);
	for (int i = 0; i < max; i++)
	{
		//if (isdigit(line[0])>0)
		if (line[0] >= '0' && line[0] <= '9')
		{
			if (i1 == num) return strtod(line,&line);
			strtod(line, &line);i1++;
		}
		else line++;
	}
	return -99999999;
}


这篇关于如何检测字符串是否以数字开头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆