C++ string类型

http://www.cplusplus.com/reference/string/string/

初始化

string a = "hello" 或 a("hello");

string b = a;

string c(2, 'c'); c = "cc",重复2次'c'字符

string d("hello", 3); d = "hel",拷贝前3个字符

string e(a, 2); e = "llo",将a字符串第2个位置开始拷贝完

string f(a,1,3); f = "ell", 从a字符串第1个位置开始拷贝3个字符

长度

a.size() 或 a.length()

判空

a.empty()

搜索

搜索以及其他的string操作是大小写敏感

string::size_type string的下标类型,一个无符号整数

string::npos 初始化为-1,表示未找到

string::size_type pos = a.find(args); 从左开始搜索第一次出现的位置,找到返回下标,否则返回npos

a.rfind(args); 从右开始搜索第一次出现的位置

args:

c, pos : 从s中位置pos开始查找字符c。pos默认为0

s2,pos : 从s中位置pos开始查找字符串s2。pos默认为0

cp,pos : 从s中位置pos开始查找指针cp指向的以空字符结尾的c风格字符串。pos默认0

cp,pos,n:从s中位置pos开始查找指针cp指向的数组的前n个字符

find原型

//string (1) 
size_type find (const basic_string& str, size_type pos = 0) const noexcept;
//c-string (2)
size_type find (const charT* s, size_type pos = 0) const;
//buffer (3)
size_type find (const charT* s, size_type pos, size_type n) const;
//character (4)
size_type find (charT c, size_type pos = 0) const noexcept;

子串拷贝

string substr(size_t pos = 0, size_t len = npos) const;

string a = b.substr(); 完整拷贝

string a = b.substr(1); 从下标位置为1开始拷贝

string a = b.substr(1, 3); 从下标位置为1开始拷贝长度为3的字符串

比较

==、!=、>、>=、<、<=

compare

string (1)
int compare (const string& str) const noexcept;
substrings (2)
int compare (size_t pos, size_t len, const string& str) const;
int compare (size_t pos, size_t len, const string& str,
             size_t subpos, size_t sublen) const;
c-string (3)
int compare (const char* s) const;
int compare (size_t pos, size_t len, const char* s) const;
buffer (4)
int compare (size_t pos, size_t len, const char* s, size_t n) const;

拼接

+=、+

遍历

下标

for (string::size_type i = 0; i < a.length(); i++) {

    a[i]

}

迭代器

string::iterator itor = a.begin()

for (; itor != a.end(); itor++) {

}

添加

string (1)
int compare (const string& str) const noexcept;
substrings (2)
int compare (size_t pos, size_t len, const string& str) const;
int compare (size_t pos, size_t len, const string& str,
             size_t subpos, size_t sublen) const;
c-string (3)
int compare (const char* s) const;
int compare (size_t pos, size_t len, const char* s) const;
buffer (4)
int compare (size_t pos, size_t len, const char* s, size_t n) const;

删除

sequence (1)
 string& erase (size_t pos = 0, size_t len = npos);
character (2)
iterator erase (const_iterator p);
range (3)
iterator erase (const_iterator first, const_iterator last);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值