zoukankan      html  css  js  c++  java
  • 把字符串转化为整数的方法

    字符串转化为整数可能是实际编程中最常用到的方法了,因为因为string很容易通过下标对每一位的数字进行操作,但是却没办法实现int的加减乘除等,所以在实际编程中经常需要先用string 存下数据,操作完后再转化为int类型

    有两种比较实用的方法可以实现

    方法一:自己写一个函数来实现

    class Solution {
    public:
        int StrToInt(string str) 
        {
            int length=str.length();//先计算字符串的长度
            if(length==0)
            {
                return 0;
            }
            int result=0;
            int flag=1;
            int i=0;
            if(str[i]=='-')//只能是在数据的首位输入符号,所以只需要一次判断即可
            {
                flag=-1;
                i++;
            }
            if(str[i]=='+')
            {
                flag=1;
                i++;
            }
            
            while(str[i]!='')
            {
                if(str[i]==' ')//删掉数字前面的空格,因为不知道前面输入了多少个空格所以需要在while循环中
                {
                    i++;
                }
                if(str[i]>='0'&&str[i]<='9')
                {
                    result=(result*10+flag*(str[i]-'0'));
                    i++;
                }
                else
                {
                    return 0;
                }
            }
            return result;
        }
    };
    

      方法二:调用库函数atio

    #include<iostream>
    #include<string>
    #include<stdlib.h>
    using namespace std;
    int main()
    {
        string str;
        cin>>str;
        int result=0;
        result=atoi(str.c_str());
        cout<<result<<endl;
        return 0;
    }
    

      stio函数的头文件是#include<stdlib.h>

    string 是C++ STL定义的类型,atoi是 C 语言的库函数,所以要先转换成 char* 类型才可以用 atoi。

    atoi函数原型

    int atoi(const char *nptr);
    

      c_str是Borland封装的String类中的一个函数,它返回当前字符串的首字符地址。

  • 相关阅读:
    php 中的 Output Control 函数
    web安全知识
    php写一个web五子棋
    实现一个web服务器, 支持php
    字节序
    TinyHTTPd源码分析
    linux 管道通信
    linux网络编程
    微信公众号开发-静默授权实现消息推送(微服务方式)
    初学 Nginx
  • 原文地址:https://www.cnblogs.com/wuyepeng/p/9741136.html
Copyright © 2011-2022 走看看