C++——STL字符串02

1.string类型的输出

#include<iostream>
#include<string>//注意不是包含(strng.h),带了.h的C的标准库
using namespace std;
int main()
{
    string str("kdhsf");
    cout<<str<<endl;//这个是重载输出运算符,但是绝对不要认为str是一个字符串
    cout<<str.c_str()<<endl;
    /*
    对于.c_str()函数其实是返回了一个char*(const 类型)类型的指针,这个指针指向的就是原来这个str
    对象里面存贮的字符串
    */
    const char *s=str.c_str();
    cout<<s<<endl;
    delete s;


system("pause");
return 0;

}

2.通过下标访问

#include<iostream>
#include<string>//注意不是包含(strng.h),带了.h的C的标准库
using namespace std;
int main()
{
    string str("khdskhg");
    cout<<str[0]<<endl;
    //cout<<str[90]<<endl; 如果下标越界,程序直接崩溃
    cout<<str.at(2)<<endl;//这个成员函数会返回一个字符
    //这个成员函数如果越界只会抛出一个异常
system("pause");
return 0;

}

3.string类型的修改

#include<string>
#include<iostream>
using namespace std;
int main()
{
    string str("kdjskl");
    str[3]='q';//第一种修改方法
    str.at(4)='q';//第二种修改方法
    cout<<str<<endl;
    return 0;

}

猜你喜欢

转载自blog.csdn.net/qq_40794602/article/details/80207801