C++STL标准模板库(一)——string类

  • String类
    • 什么是string类
    • 声明string
    • string 类型转换
    • string函数
      • 函数用法
        • s.assign()赋值
        • 对字符串元素的访问[],at()
        • 插入字符 insert()
        • 追加字符 append +=
        • 替换字符 replace()
        • 提取字符串 substr()
        • 删除字符串 erase()
        • 比较函数 compare()
        • 搜索函数 find()
        • 搜索函数 rfind()
        • 搜索函数 find_….of函数

String类

什么是string类

string类是C++标准库的一个重要的部分,也是字符串的一种数据类型,相对于char*字符串它更方便强大,我们不必担心内存是否足够、字符串长度等等,而且作为一个泛型类出现,他集成的操作函数足以完成我们大多数情况下的需要。我们可以用 = 进行赋值操作,== 进行比较,+ 做串联等

声明string

#include    // 注意这里不是string.h,string.h是C字符串头文件
    string s;//默认初始化,一个空字符串
    string s1("ssss");//s1是字面值“ssss”的副本
    string s2(s1);//s2是s1的副本
    string s3=s2;//s3是s2的副本
    string s4(10,'c');//把s4初始化
    string s5="hiya";//拷贝初始化
    string s6=string(10,'c');//拷贝初始化,生成一个初始化好的对象,拷贝给s6

    //string s(cp,n)
    char cs[]="12345";
    string s7(cs,3);//复制字符串cs的前3个字符到s当中

    //string s(s2,pos2)
    string s8="asac";
    string s9(s8,2);//从s2的第二个字符开始拷贝,不能超过s2的size

    //string s(s2,pos2,len2)
    string s10="qweqweqweq";
    string s11(s10,3,4);//s4是s3从下标3开始4个字符的拷贝,超过s3.size出现未定义

string 类型转换

string和数值转换
to_string(val) 把val转换成string
stoi(s,p,b) 把字符串s从p开始转换成b进制的int
stol(s,p,b) long
stoul(s,p,b) unsigned long
stoll(s,p,b) long long
stoull(s,p,b) unsigned long long
stof(s,p) float
stod(s,p) double
stold(s,p) long double
//string 与 const char* 之间的转换
string str = "Hello World";
const char *ch1 = str.c_str();
const char *ch2 = str.data();
//string 与 char* 之间的转换
string str = "Hello World";
int len = str.length();
char *data = new char[len+1];  //这里+1还是不+1需要注意
strcpy(data, str.c_str()); 
//char *转换成string
string str; 
const char *pc = "Hello World"; 
str = pc;
//char[ ] 转换成string
char ch [] = "ABCDEFG";
string str(ch); //也可string str = ch;12

string函数

函数名 描述
begin 得到指向字符串开头的Iterator
end 得到指向字符串结尾的Iterator
rbegin 得到指向反向字符串开头的Iterator
rend 得到指向反向字符串结尾的Iterator
size 得到字符串的大小
length 和size函数功能相同
max_size 字符串可能的最大大小
capacity 在不重新分配内存的情况下,字符串可能的大小
empty 判断是否为空
operator[] 取第几个元素,相当于数组
c_str 取得C风格的const char* 字符串
data 取得字符串内容地址
operator= 赋值操作符
reserve 预留空间
swap 交换函数
insert 插入字符
append 追加字符
push_back 追加字符
operator+= += 操作符
erase 删除字符串
clear 清空字符容器中所有内容
resize 重新分配空间
assign 和赋值操作符一样
replace 替代
copy 字符串到空间
find 查找
rfind 反向查找
find_first_of 查找包含子串中的任何字符,返回第一个位置
find_first_not_of 查找不包含子串中的任何字符,返回第一个位置
find_last_of 查找包含子串中的任何字符,返回最后一个位置
find_last_not_of 查找不包含子串中的任何字符,返回最后一个位置
substr 得到字串
compare 比较字符串
operator+ 字符串链接
operator== 判断是否相等
operator!= 判断是否不等于
operator< 判断是否小于
operator>> 从输入流中读入字符串
operator<< 字符串写入输出流
getline 从输入流中读入一行

函数用法

s.assign()赋值

s.assign(str); // 不说 
s.assign(str,1,3); // 如果str是"iamangel" 就是把"ama"赋给字符串 
s.assign(str,2,string::npos); // 把字符串str从索引值2开始到结尾赋给s 
s.assign("gaint"); // 不说 
s.assign("nico",5); // 把’n’ ‘I’ ‘c’ ‘o’ ‘\0’赋给字符串 
s.assign(5,'x'); // 把五个x赋给字符串123456

对字符串元素的访问[],at()

我们可以使用下标操作符[]和函数at()对元素包含的字符进行访问。但是应该注意的是操作符[]并不检查索引是否有效(有效索引0~str.length()),如果索引失效,会引起未定义的行为。而at()会检查,如果使用at()的时候索引无效,会抛出out_of_range异常。

提取

插入字符 insert()

在string的某个位置插入字符串,我们可以用insert()函数,我们只需要提供索引,被插入的字符串在索引的后面

//插入的不是单个字符时
s.insert(0,”my name”); 
s.insert(1,str); 
//插入的是单个字符
insert((string::size_type)0, 1, ‘j’)

追加字符 append +=

    std::string str;
    std::string str2="Writing ";
    std::string str3="print 10 and then 5 more";

    //直接追加一个str2的字符串
    str.append(str2);                       // "Writing "
    //后面追加str3第6个字符开始的3个字符串
    str.append(str3,6,3);                   // "10 "
    //追加字符串形参的前5个字符
    str.append("dots are cool",5);          // "dots "
    //直接添加
    str.append("here: ");                   // "here: "
    //添加10个'.'
    str.append(10u,'.');                    // ".........."
    //添加str3迭代器范围的字符串
    str.append(str3.begin()+8,str3.end());  // " and then 5 more"
    //最后这个比较特殊,意思是添加5个'A',实际上参数里面的65对应的asc码就是65
    str.append<int>(5,65);                // "....."
    //字符串追加也可以用重载运算符实现
    str+="lalala";

替换字符 replace()

    std::string base="this is a test string.";
    std::string str2="n example";
    std::string str3="sample phrase";
    std::string str4="useful.";

    // replace signatures used in the same order as described above:

    // Using positions:                
    std::string str=base;           // "this is a test string."
    //第9个字符以及后面的4个字符被str2代替
    str.replace(9,5,str2);          // "this is an example string." (1)
    //第19个字符串以及后面的5个字符用str的第7个字符以及后面的5个字符代替
    str.replace(19,6,str3,7,6);     // "this is an example phrase." (2)
    //第8个字符以及后面的9个字符用字符串参数代替
    str.replace(8,10,"just a");     // "this is just a phrase."     (3)
    //第8个字符以及后面的5个字符用字符串参数的前7个字符替换
    str.replace(8,6,"a shorty",7);  // "this is a short phrase."    (4)
    //第22以及后面的0个字符用3个叹号替换
    str.replace(22,1,3,'!');        // "this is a short phrase!!!"  (5)
    //迭代器的原理同上
    // Using iterators:                                               
    str.replace(str.begin(),str.end()-3,str3);                    // "sample phrase!!!"     
    str.replace(str.begin(),str.begin()+6,"replace");             // "replace phrase!!!"     
    str.replace(str.begin()+8,str.begin()+14,"is coolness",7);    // "replace is cool!!!"    
    str.replace(str.begin()+12,str.end()-4,4,'o');                // "replace is cooool!!!" 
    str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());// "replace is useful."    

提取字符串 substr()

s.substr(); // 返回s的全部内容 
s.substr(11); // 从索引11往后的子串 
s.substr(5,6); // 从索引5开始6个字符

删除字符串 erase()

  std::string str ("This is an example sentence.");
  str.erase (10,8);      
  //直接指定删除的字符串位置第十个后面的8个字符
  std::cout << str << '\n';
                            // "This is an sentence."
  str.erase (str.begin()+9);//           ^
  //删除迭代器指向的字符
  std::cout << str << '\n';
                            // "This is a sentence."
  str.erase (str.begin()+5, str.end()-9);
  //删除迭代器范围的字符
  std::cout << str << '\n';
                            // "This sentence."

比较函数 compare()

和strcmp函数一样,如果两个字符串相等,那么返回0,调用对象大于参数返回1,小于返回-1。

 string s1="123",s2="123";
    cout<//0

    s1="123",s2="1234";
    cout<//-1

    s1="1234",s2="123";
    cout<//1

    std::string str1 ("green apple");
    std::string str2 ("red apple");

    if (str1.compare(str2) != 0)
    std::cout << str1 << " is not " << str2 << '\n';
    //str1的第6个字符以及后面的4个字符和参数比较
    if (str1.compare(6,5,"apple") == 0)
    std::cout << "still, " << str1 << " is an apple\n";

    if (str2.compare(str2.size()-5,5,"apple") == 0)
    std::cout << "and " << str2 << " is also an apple\n";
    //str1的第6个字符以及后面的4个字符和str2的第4个字符以及后面的4个字符比较
    if (str1.compare(6,5,str2,4,5) == 0)
    std::cout << "therefore, both are apples\n";

搜索函数 find()

string str ("There are two needles in this haystack with needles.");
string str2 ("needle");

    // different member versions of find in the same order as above:
    //在str当中查找第一个出现的needle,找到则返回出现的位置,否则返回结尾
    std::size_t found = str.find(str2);
    //如果没找到,返回c++中一个特别的标识npos
    if (found!=std::string::npos)
    std::cout << "first 'needle' found at: " << found << '\n';
    //在str当中,从第found+1的位置开始查找参数字符串的前6个字符
    found=str.find("needles are small",found+1,6);
    if (found!=std::string::npos)
    std::cout << "second 'needle' found at: " << found << '\n';
    //在str当中查找参数中的字符串
    found=str.find("haystack");
    if (found!=std::string::npos)
    std::cout << "'haystack' also found at: " << found << '\n';
    //查找一个字符
    found=str.find('.');
    if (found!=std::string::npos)
    std::cout << "Period found at: " << found << '\n';
    //组合使用,把str2用参数表中的字符串代替
    // let's replace the first needle:
    str.replace(str.find(str2),str2.length(),"preposition");

搜索函数 rfind()

    std::string str ("The sixth sick sheik's sixth sheep's sick.");
    std::string key ("sixth");//                    ^
    //rfind是找最后一个出现的匹配字符串
    std::size_t found = str.rfind(key);
    if (found!=std::string::npos)
    {
        cout<//输出23
        str.replace (found,key.length(),"seventh");//找到的sixth替换成seventh
    }

搜索函数 find_….of函数

  • find_first_of(args) 查找args中任何一个字符第一次出现的位置
  • find_last_of(args) 最后一个出现的位置
  • find_fist_not_of(args) 查找第一个不在args中的字符
  • find_last_not_of 查找最后一个不在args中出现的字符
    std::string str1 ("Please, replace the vowels in this sentence by asterisks.");
    std::size_t found1 = str1.find_first_of("aeiou");
    //把所有元音找出来用*代替
    while (found1!=std::string::npos)
    {
        str1[found1]='*';
        found1=str1.find_first_of("aeiou",found1+1);
    }
    std::cout << str1 << '\n';

    //在str2中找到第一个不是消协英文字母和空格的字符
    std::string str2 ("look for non-alphabetic characters...");
    std::size_t found2 = str2.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");
    if (found2!=std::string::npos)
    {
        std::cout << "The first non-alphabetic character is " << str2[found2];
        std::cout << " at position " << found2 << '\n';
    }

你可能感兴趣的:(C++,C语言)