C++ primer plus系列3——string类

    技术2024-05-26  71

    string类 :将字符串当成一种数据类型,使用string处理字符串比使用数组方便;

    #include<string>//使用string类,需要包含头文件 string str;// cin>>str;//可以根据cin的输入自动调整str的长度

    1-初始化

    string str1="hello world! "; string str2={"hello world"}; string str3 {"hello world"};

    2-赋值/合并

    注意:数组之间不能赋值

    赋值 char a[7]="string"; char b[7]="hello"; a=b;//错误 string a="string"; string b="hello"; a=b;//没有问题 计算大小 cout<<a.size()<<endl; 合并 string a="hello"; string b="string"; cout<<a+b<<endl; a+=b; cout<<a<<endl; /*输出结果 hellostring hellostring */

    3-C语言中的赋值和合并操作

    #include<cstring>//之前为string.h char str[20] = "hello"; char str[10] = "string"; strcpy_s(str,str1);//copy str1 to str; strcat_s(str,str1);//拼接起来 strcat_s(str,"you"); 区别: strcat()&strncat()以及strcpy()&strncpy() 其中:strncat()strncpy()接受指出目标数组最大允许长度的第三个参数 计算大小 int len=strlen(str1);

    4-string类I/O(输出/输出)

    char a[20]; cout<<strlen(a)<<endl; //输出结果是随机的,即不一定是20,为什么呢? //由于数组a[20]用来存储字符串,因此以‘\0’作为字符串结尾,现在a[20]是未定义的,所以在计算其长度时,从第一个元素开始 直到 在内存中找到‘\0’,因此长度是随机的。 char a[20]; cin.getline(a,20);//这种句点表示法(cin.getline),表明函数getline是istream类的一个类方法;第一个参数是目标数组,第二个参数是数组长度 string b; getline(cin,b);//cin now an argument(参数) //这里没有使用句点表示法,表明这里的getline()不是类方法 //另外,也没有指出字符串长度的参数,因为string根据字符串自动调整长度

    为什么一个getline()是类方法,一个getline()不是类方法? 答:在C++引入string类之前很久,便有 istream类,因此 istream类的设计考虑到了C++的基本类型double,int等,但是没有考虑到string类; 即 istream 类中没有处理string 类对象的方法 但是,为什么cin>>a这条语句依旧可以运行? 答:友元函数—11章 string a; cin>>a;

    5-其他形式的字符串字面值(字符常量)

    还存在疑问 1-除char之外,还有wchar_t , char16_t , char32_t , 对于这些字符串字面值,C++中分别使用前缀L,u,U来表示:

    wchar_t title[]=L"good study"; char16_t name[]=u"Kevin"; char32_t age[]=U"is young";

    2-原始字符串(raw string ) 在原始字符串中,字符表示就是自己, 例如:‘\n’并不是代表换行符,而是表示两个字符:斜杠和 n

    原始字符使用“()”作为定界符,并且使用R作为标识 例如:

    //想要输出:Jim "King" Tutt uses "\n" instead of endl. cout << R"(Jim "King" Tutt uses "\n" instead of endl.)"<<endl; //使用标准的字符串字面值 cout << "Jim \"King\" Tutt uses \"\\n\" instead of endl."<<endl;

    那么,如果在原始字符串中包含 “( 或者 )” 应该怎么办? 答:在 " 和 ( 之间添加符号,值得一提的是同样的也需要在 ) 和 " 之间添加同样的符号(无论什么符号应该都可以) 例如:

    cout << R"-("(i like coding!)")-"; cout << R"+("(i like coding!)")+";
    Processed: 0.014, SQL: 9