第33课.c++中的字符串类 1.标准库中的字符串类 2.字符串与数字的转换

c++语言中没有原生的字符串类型

c++标准库提供了string类,定义后就像使用普通变量一样使用
a.string直接支持字符串连接 ("+")
b.string直接支持字符串的大小比较 (">", "<", "==", "!=")
c.string直接支持字符串的查找和提取 ()
d.string直接支持字符串的插入和替换 ()

eg:

#include <iostream>
#include <string>

using namespace std;

void string_sort(string a[], int len)
{
    for(int i = 0; i < len; i++)
    {
        for(int j = i; j < len; j++)
        {
            if(a[i] > a[j])
            {
                swap(a[i], a[j]);
            }
        }
    }   
}

string string_add(string a[], int len)
{
    string ret = "";
    
    for(int i = 0; i < len; i++)
    {
        ret += a[i] + "; ";
    }
    
    return ret;
}

int main()
{
    string sa[7] = 
    {
        "Hello World",
        "D.T.Software",
        "C#",
        "Java",
        "C++",
        "Python",
        "TypeScript"
    };
    
    string_sort(sa, 7);
    
    for(int i=0; i<7; i++)
    {
        cout << sa[i] << endl;
    }
    
    cout << endl;
    
    cout << string_add(sa, 7) << endl;
    
    return 0;
}

第33课.c++中的字符串类
1.标准库中的字符串类
2.字符串与数字的转换

2.字符串与数字的转换

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

istringstream iss("123.45");    //这里("123.45")只能是数字,不能是abc之类的
double num;
iss >> num;            //这里>>有bool返回值,成功为trun,失败为false

c.ostringstream字符串输出流
数字->string

ostringstream oss;
oss << 543.21;
string s = oss.str();        //注意:oss.str()

===
问题:abcdefg循环右移3位后得到efgabcd

    #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);
    
    // abcdefg ==> 8    (右移8位)
    // abcdefg ==> 1    (实际上只右移了1位)
    // 8 % 7   ==> 1
    
    // 7 - 1 ==> 6
    // abcdef g
    // ret ==> g
    // ret = g + abcdef
    // ret = gabcdef
    return ret; 
}

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