美文网首页
string测试

string测试

作者: XDgbh | 来源:发表于2018-07-15 18:59 被阅读3次
#include<iostream>
#include<string>
#include<stdio.h>
#include"MyString.h"

using namespace std;
int main()
{
    //1、空构造
    MyString str1;
    //2、字符串指针赋值构造
    char *cstr = "this is str2 !";
    MyString str2(cstr);
    str2.show();
    //3、拷贝赋值重载=运算符
    MyString str3;
    str3 = "this is str3";
    str3.show();
    //4、拷贝构造
    MyString str4(str3);
    str4.show();
    //重载输出<<运算符
    cout << str4<<endl;

    //使用默认的string类的各个函数
    cout << "下面开始使用标准string类:" << endl;
    string strs1 = "hfaosdogbhaisyfigbhos";
    cout <<"string串:"<< strs1 << endl;
    cout << "string串size:" << strs1.size() << endl;
    cout << "string串length:" << strs1.length() << endl;
    cout << "string串max_size:" << strs1.max_size() << endl;
    cout << "string串capacity:" << strs1.capacity() << endl;
    cout << "string串实际内存大小:" << sizeof(strs1) << endl;
    cout << "string串是否为空:" << strs1.empty() << endl;
    cout << "string串第3个元素:" << strs1[2] << endl;
    cout << "string串换成字符串:" << strs1.data() << endl;
    cout << "string串对比gbh:" << strs1.compare("gbh") << endl;
    cout << "string串的从7开始长为3的子串对比'gbh':" << strs1.compare(7, 3, "gbh") << endl;
    cout << "string串的从7开始长为4的子串对比'gbh':" << strs1.compare(7, 4, "gbh") << endl;
    cout << "string串的从7开始长为3的子串对比'wgbhw'从1开始的长为3的子串:" << strs1.compare(7, 3, "wgbhw", 1, 3) << endl;
    cout << "string串的取从7开始长为3的子串:" << strs1.substr(7, 3) << endl;
    string strs2("wgbhw");
    strs1.swap(strs2);
    cout << "string串和另一个string串'wgbhw'交换后的串:" << strs1 << endl;
    strs1.swap(strs2);  //再换回来
    cout << "string串和另一个string串再交换回来后的串:" << strs1 << endl;
    strs1 = strs1 + "WWW";
    cout << "string串+'WWW'串后:" << strs1 << endl;
    cout << "新的string串从键盘读入:";
    getline(cin, strs2);
    strs2.push_back('W');
    cout << "新的string串+一个字符'W'后:" << strs2 << endl;
    char c_str1[10] = "";
    strs1.copy(c_str1, 5);
    cout << "从string串复制数据到字符数组:" << c_str1 << endl;
    //find()函数,传入参数1子字符串地址,参数2开始查找的位置默认0
    cout << "子串gbh顺查首次出现的首字符位置在:" << strs1.find("gbh", 2) << endl;
    cout << "子串gbh倒查首次出现的首字符位置在:" << strs1.rfind("gbh", 15) << endl;
    cout << "子串gbh的任意字符开始位置:" << strs1.find_first_of("gbh") << endl;
    cout << "子串gbh的任意字符最后位置:" << strs1.find_last_of("gbh") << endl;
    cout << "子串gbh反向查找末尾字符位置:" << strs1.rfind("gbh") << endl;
    cout << "输出std::string::npos 的值:" << std::string::npos << endl;

}

相关文章

网友评论

      本文标题:string测试

      本文链接:https://www.haomeiwen.com/subject/zoappftx.html