[C++]string常用函数

1.截取子串substr

获得string的子串

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

pos
pos表示子串的起始位置。
如果pos等于字符串的长度,该函数返回一个空字符串。
如果pos大于字符串的长度,它会抛出out_of_range。
len
表示子串的长度。
string::npos表示直到字符串的结尾的所有字符。

// string::substr
#include <iostream>
#include <string>

int main ()
{
  std::string str="We think in generalities, but we live in details.";
                                           // (quoting Alfred N. Whitehead)
  std::string str2 = str.substr (3,5);     // "think"
  std::size_t pos = str.find("live");      // position of "live" in str
  std::string str3 = str.substr (pos);     // get from "live" to the end
  std::cout << str2 << ' ' << str3 << '\n';
  return 0;
}

Output:
think live in details.

str.substr(0,0);输出""

2.查找子串find

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

pos开始查找的位置
Position of the first character in the string to be considered in the search.
If this is greater than the string length, the function never finds matches.
Note: The first character is denoted by a value of 0 (not 1): A value of 0 means that the entire string is searched.
n匹配的长度
Length of sequence of characters to match.

found=str.find("needles are small",found+1,6);//实际匹配的是前6个字符needle
if (found!=std::string::npos)
    std::cout << "second 'needle' found at: " << found << '\n';

s.find(s1) 查找s中第一次出现s1的位置,并返回(包括0)
s.rfind(s1) 查找s中最后一次出现s1的位置,并返回(包括0)
s.find_first_of(s1) 查找在s1中任意一个字符在s中第一次出现的位置,并返回(包括0)
s.find_last_of(s1) 查找在s1中任意一个字符在s中最后一次出现的位置,并返回(包括0)
s.find_first_not_of(s1) 查找s中第一个不属于s1中的字符的位置,并返回(包括0)
s.find_last_not_of(s1) 查找s中最后一个不属于s1中的字符的位置,并返回(包括0)

3.添加子串append

在string后面加东西

对象原型解释
stringstring& append (const string& str);string后面接string
substringstring& append (const string& str, size_t subpos, size_t sublen);string后面接子串
c-stringstring& append (const char* s);string后面接C风格字符串
bufferstring& append (const char* s, size_t n);string后面接字符数组前n个
fillstring& append (size_t n, char c);string后面接n个c
rangetemplate <class InputIterator> string& append (InputIterator first, InputIterator last);string后面接 [first,last)
initializer liststring& append (initializer_list il);string后面接initializer list的元素

4.删除子串erase

string& erase (size_t pos = 0, size_t len = npos);
iterator erase (const_iterator p);
iterator erase (const_iterator first, const_iterator last);

str.erase(i,1)就表示删除第i个字符

5.替换子串replace

s.replace(pos, n, s1) 用s1替换s中从pos开始(包括0)的n个字符的子串

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值