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后面加东西
对象 | 原型 | 解释 |
---|---|---|
string | string& append (const string& str); | string后面接string |
substring | string& append (const string& str, size_t subpos, size_t sublen); | string后面接子串 |
c-string | string& append (const char* s); | string后面接C风格字符串 |
buffer | string& append (const char* s, size_t n); | string后面接字符数组前n个 |
fill | string& append (size_t n, char c); | string后面接n个c |
range | template <class InputIterator> string& append (InputIterator first, InputIterator last); | string后面接 [first,last) |
initializer list | string& 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个字符的子串