题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
思路:大体是分为三部分的整数、小数、带e的数,具体的判断方法在代码中
class Solution {
public:
//字符的第一个位置除了+、-、数字之外都是错的
//只有数字后面能跟'.',且'.'后面必须跟数字
//E或者e只能跟在数字后面,后面也只能跟整数数字
//因此,分为三种情况 整数、小数、带e的数
bool isinteger(char* str)//整数、小数
{
char *string=str;
if(string==NULL)
{
return false;
}
if(*string=='\0')
{
return false;
}
if(*string=='+'||*string=='-')
{
string++;
}
if(*string=='\0')//跳过加减之后没了
{
return false;
}
while(*string!='\0')
{
if(*string<'0'||*string>'9')
{
return false;
}
string++;
}
return true;
}
bool isfloat(char* string)//小数
{
char *str = string;
if(str==NULL||*str=='\0')
{
return false;
}
if(*str=='-'||*str=='+')
{
str++;
}
if(*str=='\0')
{
return false;
}
int count=0;
while(*str!='\0')
{
if((*str<'0'||*str>'9')&&*str!='.')
{
return false;
}
if(*str=='.')
{
count++;
//只要前后有一个不是数字的就返回
if(*(str+1)<'0'||*(str+1)>'9')
{
return false;
}
}
str++;
}
if(count==1)
{
return true;
}
return false;
}
bool isNumeric(char* string)
{
if(string==NULL||*string=='\0')
{
return false;
}
if(isinteger(string))
{
return true;
}
if(isfloat(string))
{
return true;
}
//判断是不是带e的数
char front[100];//在e之前的数
char back[100];//在e之后的数
char *str = string;
int index=0;//e的下标
while(*str!='\0')
{
index++;
if(*str=='e'||*str=='E')
{
break;
}
str++;
}
if(index<=1)
{
return false;
}
str = string;
int i=0;
while(i<index-1)
{
front[i]=*str;
i++;
str++;
}
front[i]='\0';
strcpy(back,str+1);
if(isinteger(front)&&isinteger(back))
{
return true;
}
if(isfloat(front)&&isinteger(back))
{
return true;
}
return false;
}
};
有些繁琐啊。。。