Validate if a given string can be interpreted as a decimal number.
Some examples:"0"
=> true
" 0.1 "
=> true
"abc"
=> false
"1 a"
=> false
"2e10"
=> true
" -90e3 "
=> true
" 1e"
=> false
"e3"
=> false
" 6e-1"
=> true
" 99e2.5 "
=> false
"53.5e93"
=> true
" --6 "
=> false
"-+3"
=> false
"95a54e53"
=> false
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number:
- Numbers 0-9
- Exponent - "e"
- Positive/negative sign - "+"/"-"
- Decimal point - "."
Of course, the context of these characters also matters in the input.
一开始好乱,看了个答案慢慢理。
输入是有包含空格的,所以要先处理空格。C++中string带的函数还挺多的,详见博客。
s.length()和s.size()的数值相同 前者返回字符串长度,后者返回字符串中现在拥有的字符数。
s.substr(index,num) 本字符串的一个子串,从index开始,长num个字符,如果只有一个值s.substr(index)默认从index开始后面的所有字符。
s.find(), s.find_first_of(), s.find_first_not_of(), s.find_last_of(), s.find_last_not_of() 查找某个字符串,返回位置
s.begin(), s.end() 函数返回一个迭代器,指向字符串的第一个/最后一个元素.
s.at(index) 函数返回一个引用,指向在index位置的字符
处理完空格之后找规律,以‘e’分开前后,前面只可能是小数,后面只可能是整数,正负都有可能,而且正负号后面紧跟数字。再找小数点,一小数点分开前后肯定是整的。
C++版本。
#include <iostream>
using namespace std;
//处理空格
void trimString(string &s){
int pos = s.find_first_not_of(" ");
if(pos != -1){
s = s.substr(pos);
}
pos = s.find_last_not_of(" ");
if(pos != -1){
s.erase(s.begin()+pos+1,s.end());
}
}
bool isPositiveInt(string s){
if(s.size()==0) return false;
for(int i=0;i<s.size();i++){
char c=s[i];
if(c<'0' || c>'9') return false;
}
return true;
}
bool isInt(string s){
if(s[0]=='-'||s[0]=='+'){
s = s.substr(1);
}
return isPositiveInt(s);
}
bool isFloat(string s){
if(s[0]=='-'||s[0]=='+'){
s = s.substr(1);
}
if(s.size()==1) return isInt(s);
int pos = s.find('.');
if(pos==-1){
return isPositiveInt(s);
}else if(pos==0){//.1
return isPositiveInt(s.substr(1));
}else if(pos==s.size()-1){
s.erase(pos);
return isPositiveInt(s);
}else{
return isPositiveInt(s.substr(0,pos))&&isPositiveInt(s.substr(pos+1));
}
}
bool isNumber(string s) {
trimString(s);
int len = s.length();
if(len==0) return false;
int pos = s.find('e');//找e
if(pos==0||pos==s.size()-1) return false;//first last
if(pos==-1) return isFloat(s);//not find
else{//e前面可能是float,后面只可能是Int
return isFloat(s.substr(0,pos)) && isInt(s.substr(pos+1));
}
}
int main(){
string s;
getline(cin,s);//读取一行
int b = s[0];
int m = '-';
//trimString(s);
cout<<s.length()<<endl;
bool a=isNumber(s);
if(a==0) cout<<"false"<<endl;
else cout<<"true"<<endl;
return 0;
}
Python版本。待补充