字符串类

C语言中用字符数组和一组字符操作函数实现对字符串的操作。

C++中用一个类类型实现一个字符串。

string 类:类提供字符串的连接,大小比较(排序),查找,提取,插入,替换等功能。

      头文件<string>

 

sstream类: 字符串流类(sstream)用于字符串的转化

                     头文件<sstream> 。istringstream字符串输入流。ostringstream字符串输出流。

isstringstream iss("123");  //定义一个字符串输入流,将 “123” 输入到 iss 流对象里
int num ;       
iss >> num;    // 将流对象 iss 出入到 num 对象。库函数重载了>>表达式,传输成功表达式为ture,传输失败表达式为false。

ostringstream oss; //定义字符串输出流对象
oss << 123;       // 将123传输到输出流对象。库函数重载了>>表达式,传输成功表达式为ture,传输失败表达式为false。
string s = oss.str(); //通过流对象字符串函数得到对应的函数

 

 

 字符串转数字,数字转字符串

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

#define TO_NUMBER(s, n) (istringstream(s) >> n) //定义了一个istringstream的临时对象     
                                                //将调用类的字符串转化函数
                                                
#define TO_STRING(n)    (((ostringstream() << n)).str()) //定义了一个类型为ostringstream的临时对象
                                                         //并将条用类的转化函数
                                                         //再调用对象内部str函数输出字符串

int main()
{
    double n = 0;
   
    if( TO_NUMBER("234.567", n) )
    {  cout << n << endl;  }

    string s = TO_STRING(12345);
    cout << s << endl;     
    
    return 0;
}

 

 

重载加 >> 操作符字符串右移功能

#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();  //  string类的length函数求字符串长度
    pos = s.length() - n;
    ret = s.substr(pos);  //  string类的substr函数获取pos后的字符串
    ret += s.substr(0, pos);  //  string类的substr函数获取0到pos中间的字符串
    
    return ret;
}

int main()
{
    string s = "abcdefg";
    string r = (s >> 3);
    
    cout << r << endl;
    
    return 0;
}

 

posted @ 2019-05-08 18:37  张不源  Views(183)  Comments(0Edit  收藏  举报