用 C++ 编写自己的 atoi()
atoi() 函数在 c 编程语言中用于处理字符串到整形的转换。此函数接受字符串作为输入并返回整数类型的转换结果。
语法
int atoi(const char string)
接受的参数 - atoi() 函数接受字符串作为输入,然后将该字符串转换为等效的整数。
返回类型 - 此函数返回一个整数。对于有效字符串该值将是等效的整数,否则函数将返回 0。
atoi() 函数的实现 -
我们将遍历字符串的每个字符,并将该数字乘以 10 并添加到前面结果中来创建整数。
对于负整数,我们将检查字符串的第一个字符是否为 -,如果是,我们将最终结果乘以 -1。
我们将检查字符串是否有效,即检查字符串中的每个字符是否介于 0 到 9 之间。
演示我们解决方案实现的程序,
示例
#include <iostream>
using namespace std;
bool isNumericChar(char x) {
return (x >= '0' && x <= '9') ? true : false;
}
int myAtoi(char* str) {
if (*str == '\0')
return 0;
int result = 0;
int sign = 1;
int i = 0;
if (str[0] == '-') {
sign = -1;
i++;
}
for (; str[i] != '\0'; ++i) {
if (isNumericChar(str[i]) == false)
return 0;
result = result * 10 + str[i] - '0';
}
return sign * result;
}
int main() {
char string[] = "-32491841";
int intVal = myAtoi(string);
cout<<"The integer equivalent of the given string is "<<intVal;
return 0;
}输出
The integer equivalent of the given string is -32491841
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP