检查给定的字符串是否在 C++ 中是有效数字
概念
应验证给定的字符串是否是数字。
输入 − str = "12.5"
输出 − true
输入 − str = "def"
输出 − false
输入 − str = "2e5"
输出 − true
输入 − 10e4.4
输出 − false
方法
我们必须在代码中处理以下情况。
我们必须忽略前导和尾随空格。
我们必须忽略开始处的“+”、“-”和“.”。
我们必须确保字符串中的字符属于 {+, -, ., e, [0-9]}。
我们必须确保“.”后面没有“e”。
数字应跟在点字符“.”后面。
我们必须确保字符“e”后面应跟着“+”、“-”或数字。
示例
// C++ program to check if input number
// is a valid number
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int valid_number1(string str1){
int i = 0, j = str1.length() - 1;
while (i < str1.length() && str1[i] == ' ')
i++;
while (j >= 0 && str1[j] == ' ')
j--;
if (i > j)
return 0;
if (i == j && !(str1[i] >= '0' && str1[i] <= '9'))
return 0;
if (str1[i] != '.' && str1[i] != '+' && str1[i] != '-' && !(str1[i] >= '0' && str1[i] <= '9'))
return 0;
bool flagDotOrE = false;
for (i; i <= j; i++) {
// If any of the char does not belong to
// {digit, +, -, ., e}
if (str1[i] != 'e' && str1[i] != '.'
&& str1[i] != '+' && str1[i] != '-'
&& !(str1[i] >= '0' && str1[i] <= '9'))
return 0;
if (str1[i] == '.') {
if (flagDotOrE == true)
return 0;
if (i + 1 > str1.length())
return 0;
if (!(str1[i + 1] >= '0' && str1[i + 1] <= '9'))
return 0;
}
else if (str1[i] == 'e') {
flagDotOrE = true;
if (!(str1[i - 1] >= '0' && str1[i - 1] <= '9'))
return 0;
if (i + 1 > str1.length())
return 0;
if (str1[i + 1] != '+' && str1[i + 1] != '-'
&& (str1[i + 1] >= '0' && str1[i] <= '9'))
return 0;
}
}
return 1;
}
// Driver code
int main(){
char str1[] = "0.1e10";
if (valid_number1(str1))
cout << "true";
else
cout << "false";
return 0;
}输出
true
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP