📌  相关文章
📜  c++ 获取两个字符之间的字符串 - C++ (1)

📅  最后修改于: 2023-12-03 14:39:56.054000             🧑  作者: Mango

C++ 获取两个字符之间的字符串

在C++中,获取两个字符之间的字符串可以使用substr()函数和find()函数。其中substr()函数用于获取从指定位置开始的指定长度的子字符串,而find()函数用于查找指定字符在字符串中的位置。结合使用这两个函数,就可以获取两个字符之间的字符串了。

substr()函数
string substr (size_t pos, size_t len) const;
string substr (size_t pos) const;

substr()函数接受两个参数,第一个参数表示从哪个位置开始获取子字符串,第二个参数表示子字符串的长度,如果不指定第二个参数则默认获取从指定位置到字符串结尾的所有字符。该函数返回一个新的字符串对象,包含了指定范围内的所有字符。

例如,获取字符串s中从位置3开始长度为5的子字符串:

string s = "hello, world!";
string sub_s = s.substr(3, 5);

得到的sub_s为"lo, w"。

find()函数
size_t find (const string& str, size_t pos = 0) const noexcept;
size_t find (const char* s, size_t pos, size_t n) const;
size_t find (const char* s, size_t pos = 0) const;
size_t find (char c, size_t pos = 0) const noexcept;

find()函数接受一个参数,表示要查找的字符或字符串,另外还可以通过第二个参数指定查找的起始位置。该函数返回要查找的字符或字符串在目标字符串中第一次出现的位置,如果没找到则返回string::npos。

例如,查找字符串s中字符"o"的位置:

string s = "hello, world!";
size_t pos = s.find('o');

得到的pos为4。

获取两个字符之间的字符串

结合使用substr()函数和find()函数,可以获取两个字符之间的字符串。例如,获取字符串s中字符"o"和字符","之间的子字符串:

string s = "hello, world!";
size_t start_pos = s.find('o');
size_t end_pos = s.find(',');
string sub_s = s.substr(start_pos+1, end_pos-start_pos-1);

首先使用find()函数获取字符"o"的位置,然后使用find()函数获取字符","的位置,最后使用substr()函数获取指定范围内的子字符串。其中,start_pos+1表示从字符"o"的下一个字符开始获取,end_pos-start_pos-1表示要获取的字符的长度。得到的sub_s为"llo".