zoukankan      html  css  js  c++  java
  • 字符串转换为整数

    下面代码仅供本人复习所用,实用性N低,各位飘过吧~~哈哈:>

    //
    // 字符串转换为整数. 
    // 
    
    #include <cstdlib>
    #include <iostream>
    #include <string>
    
    long toInteger(const std::string &str)
    {
    	bool isNegative = false; 
    	long result = 0;
    	size_t i;
    	const size_t length = str.length();
    	
    	//
    	// 跳过非数字或符号的字符. 
    	//
    	for (i = 0; i < length && ('0' > str[i] || '9' < str[i]); ++i) 
    	{ 
    		//
    		// 处理负号. 
    		//
    		if ('-' == str[i] && '0' <= str[i + 1] && '9' >= str[i + 1]) 
    		{
    			isNegative = true;
    			i++;
    			break;
    		}
    	}
    
    	//
    	// 处理数字.
    	//
    	while (i < length && '0' <= str[i] && '9' >= str[i])
    	{
    		result = 10 * result + (str[i++] - '0');
    	}
    	
    	return true == isNegative ? result * -1 : result;
    }
    
    int main(void)
    {
    	std::cout << toInteger("123456") << std::endl;
    	std::cout << toInteger("-123456") << std::endl; 
    	std::cout << toInteger("--123456-") << std::endl; 
    	std::cout << toInteger("abBsD-123456") << std::endl; 
    	std::cout << toInteger("abBsD-123456XddeE") << std::endl; 
    	std::cout << toInteger("abBsD123456XddeE") << std::endl;
    	return EXIT_SUCCESS;
    }
    
  • 相关阅读:
    第四周技术博客发表 线性表
    《我是一只IT小小鸟》读后感
    java9最新发布
    MD5进行解密操作
    MD5进行加密操作
    定时器的编写
    mybatis查询修改同时操作
    java8的版本对组合式异步编程
    linux中安装gcc
    linux不能上网问题
  • 原文地址:https://www.cnblogs.com/wxxweb/p/2067351.html
Copyright © 2011-2022 走看看