C++ string字符串类型相关知识点

string::size_type

字符串的size()成员函数应该似乎返回整型数值,但事实上str.size()返回是string::size_type类型的值

string类型和其他许多库类型都定义了一些配套类型(companion type)。通过这些配套类型,库函数的使用就与机器无关(machine-independent)。

size_type与unsigned型(unsigned int  或 unsigned long)具有相同含义,而且保证足够大的能够存储任意的string对象的长度。

string::size_type它在不同的机器上,长度是可以不同的,并非固定的长度。但只要你使用了这个类型,就使得你的程序适合这个机器。与实际机器匹配。

注意:不要把size的返回值赋给一个int变量,一是unsigned 和 signed的大小问题,二是有些机器上int变量的表示范围太小.因此,为了避免溢出,保存一个string对象size的最安全的方法就是使用标准库类型string::size_type.

string对象的索引也应为size_type类型。

string::npos表示size_type的最大值,用来表示不存在的位置

find()成员函数的返回值为size_type

返回size_t或size_type的有sizeof(),strlen(),size()

#include <iostream>
using namespace std;
int main(){
    string s1 = "Hello";
    string::size_type count = 5;
    int c = 0;
    long k = 0;
    count=s1.find("w");
    c = s1.find("w");                  //str.find()成员函数的返回值为size_type
    bool flag1 = (count == string::npos);
    bool flag2 = (c == string::npos);
    cout<<"flag1:"<<flag1<<endl<<"flag2:"<<flag2<<endl;
    cout<<"size_type:"<<count<<endl<<"int:"<<c<<endl;
    cout<<"string::pos值:"<<string::npos<<endl;   //npos表示size_type的最大值,用来表示不存在的位置
    cout<<"size of int:"<<sizeof(c)<<endl;
    cout<<"size of size_type:"<<sizeof(count)<<endl;
    cout<<"size of long:"<<sizeof(k)<<endl;//int long 并不是绝对的大小关系 这里都是4个字节32位
}
//输出
flag1:1 flag2:1 size_type:18446744073709551615 int:-1                    //返回-1表示不存在的位置 string::pos值:18446744073709551615  //因为它是无符号的,所以不是-1 size of int:4 size of size_type:8 size of long:4

 string::find()方法和string::nopos静态常量  (noposition)

string::find()函数:是一个字符或字符串查找函数,该函数有唯一的返回类型string::size_type,即一个无符号整形类型,可能是整数也可能是长整数。如果查找成功,返回按照查找规则找到的第一个字符或者子串的位置;如果查找失败,返回string::npos,即-1(当然打印出的结果不是-1,而是一个很大的数值,那是因为它是无符号的)。

string::npos静态成员常量:是对类型为size_t的元素具有最大可能的值。当这个值在字符串成员函数中的长度或者子长度被使用时,该值表示“直到字符串结尾”。作为返回值他通常被用作表明没有匹配

string::npos是这样定义的:static const size_type npos = -1;

因为string::size_type描述的是size,故需为无符号整数型类别。因为缺省配置为size_t作为size_type,于是-1被转换为无符号整数类型,npos也就成为了该类别的最大无符号值。不过实际值还是取决于size_type的实际定义类型,即无符号整型(unsigned int)的-1与无符号长整型(unsigned long)的-1是不同的

push_back()方法

string中的push_back函数,作用是字符串之后插入一个字符。字符串末尾加单个字符

 C++ 中的vector头文件里面就有这个push_back函数,在vector类中作用为在vector尾部加入一个数据。

原文地址:https://www.cnblogs.com/hemengjita/p/12747173.html