第 33课 C++中的字符串(下)

字符串与数字转换
-标准库中提供了相关的类对字符串和数字进行转换
-字符串流类(sstream)用于string的转换
.<sstream>-相关头文件
.istringstream-字符串输入流
.ostringstream-字符串输出流

使用方法
-string-->数字
istringstream iss("123.45");
double num;
iss >> num

数字--->string
ostringstream oss;
oss << 543.21
string s = oss.str();

字符串和数字的转换

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    istringstream iss("123.45");
    double num;
    //iss >> num;  //重载 >> 有返回值,返回值是一个bool类型
    if(iss >> num)
    {
         cout << num <<endl;
    }

    ostringstream oss;
    //oss << 543.21;  //这个地方也有返回值,返回值就是oss对象本身。如何证明呢?
    oss << 543 << '.' << 21;
    string s = oss.str();
    cout << s <<endl;

    return 0;
}
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

//这个程序不够完美,为什么?因为函数的参数为double类型,那么int类型的呢?需要将这个函数再写一遍吗,这样可以,但是就是
//在造轮子。目前我们还无法使用更高级的用法,比如说模板技术。但是在这里可以通过使用C语言中的宏实现。

#if 1
#define TO_NUMBER(s,n) (istringstream(s) >> n) //这个地方就是利用前面学过的调用构造函数产生临时对象,临时对象的生命周期只在这一条语句中。
#define TO_STRING(n)   (((ostringstream&)(ostringstream() << n)).str())
#else
bool to_number(const string& s, double &n)
{
    istringstream ss(s);

    return ss >> n;
}

string to_string(double n)
{
    return ((ostringstream&)(ostringstream() << n)).str();
}
#endif
int main()
{
    double n;
    if(TO_NUMBER("123.45",n))
    {
         cout << n <<endl;
    }

    string s = TO_STRING(2.1345);
    cout << s <<endl;

    return 0;
}

字符串右移
-示例:
.  abcdefg循环右移3位后得到efgabcd

#include <iostream>
#include <string>

using namespace std;

string right_func(const string& s, unsigned int n)
{
    string ret = "";
    unsigned int pos = 0;

    n = n % s.length();
    pos = s.length() - n;
    ret = s.substr(pos);
    ret += s.substr(0, pos);

    return ret;
}

int main()
{
    string s = "abcdefg";
    string r = right_func(s,1);

    cout << r << endl;

    return 0;
}

这种写法就非常简练,不像C语言中,有指针在移动。但是我感觉还不够酷炫,我直接重载 >> 这个操作符。

#include <iostream>
#include <string>

using namespace std;

string operator >> (const string& s, unsigned int n)
{
    string ret = "";
    unsigned int pos = 0;

    n = n % s.length();
    pos = s.length() - n;
    ret = s.substr(pos);
    ret += s.substr(0, pos);

    return ret;
}

int main()
{
    string s = "abcdefg";
    string r = s >> 1;

    cout << r << endl;

    return 0;
}
原文地址:https://www.cnblogs.com/-glb/p/11914856.html