• 把字符串转化为整数的方法


    字符串转化为整数可能是实际编程中最常用到的方法了,因为因为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类中的一个函数,它返回当前字符串的首字符地址。

  • 相关阅读:
    win10- *.msi 软件的安装,比如 SVN安装报2503,2502
    Java-byte[]与16进制字符串互转
    log4j 日志脱敏处理 + java properties文件加载
    CentOS7编译安装SVN(subversion1.9.7)
    Samba安装与配置
    php 实现redis发布订阅消息及时通讯
    PHP中使用ActiveMQ实现消息队列
    sphinx 配置文件全解析
    nginx和apache 配置
    php实现汉诺塔问题
  • 原文地址:https://www.cnblogs.com/wuyepeng/p/9741136.html
Copyright © 2020-2023  润新知