개념
주어진 문자열이 숫자인 경우 유효성을 검사해야 합니다.
입력 - str ="12.5"
출력 - 사실
입력 - str ="def"
출력 - 거짓
입력 - str ="2e5"
출력 - 사실
입력 − 10e4.4
출력 - 거짓
방법
코드에서 다음과 같은 경우를 처리해야 합니다.
-
선행 및 후행 공백을 무시해야 합니다.
-
시작 부분의 '+', '-' 및'.'는 무시해야 합니다.
-
문자열의 문자가 {+, -, ., e, [0-9]}
에 속하는지 확인해야 합니다. -
'.'가 ''' 뒤에 오지 않도록 해야 합니다.
-
숫자는 점 문자 '.' 다음에 와야 합니다.
-
'+', '-' 또는 숫자가 '문자' 다음에 와야 합니다.
예시
// 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