string 和 integer之间转换

Implement atoi to convert a string to an integer.

class Solution {
public:
    int myAtoi(string str) {
        if(str.size() == 0)
            return 0;
        int pos = 0;
        while(str[pos] == ' ')
            pos ++;
        bool isPositive = true;
        if(str[pos] == '-'){
            isPositive = false;
            pos++;
        }
        else if(str[pos] == '+'){
            isPositive = true;
            pos++;
        }
        if(str[pos] < '0' || str[pos] >'9')
            return 0;
        int val = 0;
        while(str[pos] >= '0' && str[pos] <= '9')
        {
            if(val > INT_MAX/10 ||((val == INT_MAX/10) && str[pos] - '0' >= 8))
                return isPositive?INT_MAX:INT_MIN;
            val = val *10 + str[pos]-'0';
            ++pos;
        }
        if(isPositive)
            return val;
        else
            return -val;
    }
};

interger to string

string itos(int x){
   int val = (x>=0)? x:-x;
   string res;
   while(val){
      res = char(val%10+'0') + res;
      val = val/10;
   }
   if(x < 0)
      res = '-'+res;
   return res;
}

 
还可以通过stringstream实现转换(需include<sstream>)

string str = "123234afi";
int num;
stringstream ss;
ss<<str;
ss>>num;   // num返回123234;如果str="123 23",num 返回123;如果str = "ab123",num返回0
int num = -234;
stringstream ss;
string file;
ss<<num;
ss>>file;

stringstream重新使用时应该清理掉
ss.str(“”);
ss.clear();
另外,C++11引入to_string()能将数值类型转换为string类型。

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
Convert numerical value to string
Returns a string with the representation of val.

Leave a Reply

Your email address will not be published. Required fields are marked *