本文共 3100 字,大约阅读时间需要 10 分钟。
C语言中的 atoi
函数用于将字符串转换为整数。但在实现这一功能时,需要考虑多种不同的输入情况。这些情况包括处理空白字符、符号、数字以及其他无效字符。
在实现 atoi
函数之前,我们需要考虑以下几种输入情况:
null
,函数应返回0。+
或-
,可以出现在字符串的开头。INT_MAX
或 INT_MIN
。++2
、+--2
等,应认为是无效的输入。INT_MAX
或 INT_MIN
。public class Atoi { public static int atoi(String str) { // Null或空字符串 if (str == null || str.isEmpty()) { return 0; } // 去空白符 String trimmedStr = str.trim(); if (trimmedStr.isEmpty()) { return 0; } int result = 0; boolean sign = true; // 正数,false为负数 int index = 0; // 遍历字符串 for (int i = 0; i < trimmedStr.length(); i++) { char c = trimmedStr.charAt(i); // 检查是否是符号 if (c == '+' || c == '-') { if (sign) { // 符号只能出现一次 sign = false; index = i + 1; } else { // 多个符号符号,返回零 return 0; } } else if (Character.isLetterOrDigit(c) || c == ' ') { // 有字母或数字或空白符 continue; } else { // 遇到其他字符,返回零 return 0; } // 处理数字 try { int number = Character.getNumericValue(c); result = result * 10 + number; // 检查是否溢出 if (result > Integer.MAX_VALUE && sign) { return Integer.MAX_VALUE; } if (result < Integer.MIN_VALUE && !sign) { return Integer.MIN_VALUE; } } catch (NumberFormatException e) { // 当字符不是数字时,抛出异常,但逻辑上这里不应该出现 return 0; } } return result; } // 测试代码 public static void main(String[] args) { System.out.println(atoi("123")); // 123 System.out.println(atoi("-123")); // -123 System.out.println(atoi("+456")); // 456 System.out.println(atoi(" 789")); // 789 System.out.println(atoi(" -012")); // 12,因为前导零没有意义 System.out.println(atoi("abc")); // 0 System.out.println(atoi("+")); // 0 System.out.println(atoi("++123")); // 0 System.out.println(ато("+2"));//2 System.out.println(arti("2")); //2 }}
trim
方法去除字符串前后的空白符,处理为空的情况。Character.getNumericValue
获取数字符号的数值。这个实现尽量覆盖了大部分可能的输入情况,包括了边界情况处理,并通过测试确认能够正确转换各种有效的整数字符串。
转载地址:http://rmgyk.baihongyu.com/