6.string字符串存取

2021-04-05  本文已影响0人  lxr_
#include<iostream>
using namespace std;

//string 单个字符获取的两种方式

//1.char& operator[](int n)通过[]方式取字符
//2.char& at(int n)        通过at方法获取字符

void test0601()
{
    string str1 = "hello";

    cout << "str1=" << str1 << endl;

    //1.通过[]访问单个字符

    for (int i = 0; i < str1.size(); i++)
    {
        cout << str1[i] << " ";
    }
    cout << endl;

    //2.通过at方法访问单个字符
    for (int i = 0; i < str1.size(); i++)
    {
        cout << str1.at(i) << " ";
    }
    cout << endl;

    //修改单个字符
    str1[0] = 'x';
    cout << "str1=" << str1 << endl;

    str1.at(1) = 'x';
    cout << "str1=" << str1 << endl;

}

int main()
{

    test0601();

    system("pause");
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读