要用C++写才行
我用java写的,希望对你有用
public int atoi(String s)
{
int s_index = 0; //string index, for conversion
byte num_sign = 1; //sign of the result number
int number = 0; //result number
//check the input string length
if (s.length() <= 0)
{ System.out.println("input string length is incorrect. should be larger than 0");
return 0;
}
//System.out.println("input string is "+s);
//check the sign
if (s.charAt(0) == '-' || s.charAt(0) == '+')
{ if (s.charAt(0) == '-')
num_sign = -1;
s_index = 1;
}
for (int i=s_index; i<s.length(); i++)
{
if (s.charAt(i) >= '0' && s.charAt(i) <= '9')
{
//System.out.println("string at "+i+" is "+s.charAt(i));
number = number*10 + (s.charAt(i) - '0');
}
else {
if (s.charAt(i) != '.')
System.out.println("input string has wrong characters. should be digits 0-9");
break;
}
}
return num_sign*number;
}
public int atoi(String s)
{
int s_index = 0; //string index, for conversion
byte num_sign = 1; //sign of the result number
int number = 0; //result number
//check the input string length
if (s.length() <= 0)
{ System.out.println("input string length is incorrect. should be larger than 0");
return 0;
}
//System.out.println("input string is "+s);
//check the sign
if (s.charAt(0) == '-' || s.charAt(0) == '+')
{ if (s.charAt(0) == '-')
num_sign = -1;
s_index = 1;
}
for (int i=s_index; i<s.length(); i++)
{
if (s.charAt(i) >= '0' && s.charAt(i) <= '9')
{
//System.out.println("string at "+i+" is "+s.charAt(i));
number = number*10 + (s.charAt(i) - '0');
}
else {
if (s.charAt(i) != '.')
System.out.println("input string has wrong characters. should be digits 0-9");
break;
}
}
return num_sign*number;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答 2011-03-10
如果我没有理解错的话,你逐个字符判断它们的ASCII码值啊。1~9的ASCII代码是从48到57。如果该字符的ASCII码值在这个范围内,就是数字,其他的就不是。
不知道楼主要求的东西是不是这个~
不知道楼主要求的东西是不是这个~