关于c++中字符串类的一些描述

1 string 类的使用,要包含头文件 #include <string>

2 两个string类可以相加,但不能相减

比如说:string s1,s2,s3;

s1="asd";

s2="qw";

s3=s1+s2 则s3="asdqw"

s3=s2+s1 则s3="qwasd";

3 两个字符串还可以比较大小 可以用< > == 使用if语句对2个字符串类直接进行比较

规则是这样的,先比较第一个字符,如果相等,则比较第二个,以此类推,只要比较到哪个字符大,就结束比较

s1="asd";
s2="at"//则s2>s1

s1="asd";
s2="as"//则s2<s1

s1="asd";
s2="asd"//则s2==s1

4 关于一些字符串函数的使用

    4.1 求字符串中第几个字符是什么

 1 int main(int argc , char *argv[])
 2 {
 3     string s1,s2,s3;
 4     char a;
 5     s1="asd";
 6     s2="at";
 7     a=s1.at(0);//则a='a'
 8         a=s1.at(1);//则a='s'
 9         a=s1.at(2);//则a='d'
10         a=s1.at(3);//越界了系统会主动报错
11     cout<<a<<endl;
12     return 0;
13 }

      4.2 求字符串长度

     s1="asd";

    b=s1.size();//则b等于3

      4.3 判断一个字符串是否为空

 1 #include <iostream>
 2 #include <string>
 3 using namespace std ;
 4 int main(int argc , char *argv[])
 5 {
 6     string s1,s2,s3;
 7     char a;
 8     int b;
 9     s1="asd";
10     s2="at";
11     b=s1.empty();
12     cout<<b<<endl;//输出0
13     b=s3.empty();
14     cout<<b<<endl;//输出1
15     return 0;
16 }

    4.4 求子字符串

   str2  =  str1. substr(2, 4);  // 从下标2 开始的4 个字符, 

      下标是从0开始算起的,需要注意的是,比如s1从下标2开始后面没有4个字符,最多只有3个字符,则str2也只有3个字符

   4.5查找子字符串
     n = str1.find("DEF",pos); // 从 pos 开始查找字符串 "DEF" 在 str1 中的位置

  

 1 #include <iostream>
 2 #include <string>
 3 using namespace std ;
 4 int main(int argc , char *argv[])
 5 {
 6     string s1,s2,s3;
 7     char a;
 8     int b;
 9     s1="asDEFDEF";
10     b = s1.find("DEF",0);//当查找的位置为0,1,2时,b都为2,当查找的位置为3,4,5时,b为5,当查找的位置大于5时,b为-1
11     cout<<b<<endl;
12 
13     return 0;
14 }


  4.6 删除字符
  str1.erase(3, 5); // 从下标3 开始往后删5 个字符

  如果后面的字符不足5个则不删了


   4.7增加字符
   str1.append("12345",1,3); // 在 str1 末尾增加 "12345" 下标从1 开始的3 个字符,即 "234"  如果个数不足,则就不加了

   4.8字符串替换和插入操作
   str1.replace(p0,n0,S1, n); // 删除从 p0 开始的 n0 个字符,然后在 p0 处插入字符串S1 前n个字符
   str1.replace(p0,n0,str2, pos, n); // 删除从 p0 开始的 n0 个字符,然后在 p0 处插入字符串 str2 中 pos 开始的前n个字符

   str1.insert(p0, S1, n); // 在 p0 位置插入字符串 S1 前n 个字符
   str1.insert(p0, str2, pos, n); // 在 p0 位置插入字符串 str2 中 pos 开始的前n 个字符

原文地址:https://www.cnblogs.com/tiantiantian-dianzi/p/5651996.html