C++string类总结

  • 要使用 string 类,必须包含头文件 <string>
  • 实质**\0** 结尾的字符数组
  • 定义与输入
string s;
cin >> s;
  • string的函数和用法
  1. 构造函数
string strs //生成空字符串
string s(str) //生成字符串str的复制品
string s(str, stridx) //将字符串str中始于stridx的部分作为构造函数的初值
string s(str, strbegin, strlen) //将字符串str中始于strbegin、长度为strlen的部分作为字符串初值
strings(num, c) //生成一个字符串,包含num个c字符
strings(strs, beg, end)    //以区间[beg, end]内的字符作为字符串s的初值
  1. 析构函数(基本不用)~string() //销毁所有内存,释放内存
  2. 有关大小和容量的成员函数
string s("abcdefg");
cout<<s.size()<<s.length();

结果都为7

  1. 赋值
string s1("abcdefg");
string s2;
s2.assign(s1);
s2 = s1; //与上等同作用
  1. 交换两个字符串
string s1("abcdefg");
string s2("1234567");
swap(s1,s2);

string s3;
s3 = s1;
s1 = s2;
s2 = s3;

两种方法

  1. 添加字符(串)
string s1("abcdefg");
string s2("1234567");
s1 = s1+s2;
cout<<s1<<endl;
s1 = s1+"hhhh";
cout<<s1<<endl;
s1.append("sdf");
cout<<s1<<endl;

abcdefg1234567
abcdefg1234567hhhh
abcdefg1234567hhhhsdf
replace()

basic_string& replace( size_type pos, size_type count,
                       const basic_string& str,
                       size_type pos2, size_type count2 = npos );
basic_string& replace( size_type pos, size_type count,
                       size_type count2, CharT ch ); 
basic_string& replace( const_iterator first, const_iterator last,
                       size_type count2, CharT ch );
basic_string& replace( const_iterator first, const_iterator last,
                       const basic_string& str );
basic_string& replace( size_type pos, size_type count,
                       const basic_string& str,
                       size_type pos2, size_type count2 );                      
参数
pos 将被替换的子串起始位置 
count 将被替换的子串长度 
first, last 将被替换的字符范围 
str 用于替换的 string 
pos2 用于替换的子串起始位置 
count2 用于替换的字符数 
ch 用于替换的字符值 
first2, last2 用于替换的字符范围 
  1. empty ()判断字符串是否为空
  2. ==,! =,<,<=,>,>=,compare() 比较字符串内容
  3. find()
    搜寻某子字符串或字符
str.find(str2) 
当str2是str的字串时,返回其在str中第一次出现的位置;
如果str2不是str的字串,返回string::npos (-1;

附:(c++所有成员函数)
在这里插入图片描述

其中substr中两个参数分别是第一个字符的位置,第二个参数是要字符的长度
以空格分隔字符串的方法

class Solution {
public:
    int isPrefixOfWord(string sentence, string searchWord) {
        istringstream ss(sentence);
        string str;
        for (int i = 1; ss >> str; i ++)
            if (str.find(searchWord) == 0) return i;
        return -1;
    }
};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值