C++字符串复习
C++字符串复习
前言
为了保证复习高效,以下不包括很简单的内容,例如cin。
C类型字符、字符串
输入方法
- **
char c = getchar()
**输入单个字符
string类型字符串
输入方法
getline(cin, str)
整行输入
常用方法
-
s.substr(pos, len)
:截取字符串s
,从第pos
个位置开始,截取len
个字符,并返回这个子字符串。string s = "Hello, World!"; string sub = s.substr(7, 5); // "World"
-
s.insert(pos, str)
:在字符串s
的第pos
个位置之前,插入字符串str
,并返回修改后的字符串。string s = "Hello!"; s.insert(5, ", World"); // "Hello, World!"
-
s.find(str, [pos])
:在字符串s
中,从第pos
个字符开始寻找子字符串str
,并返回其起始位置。如果找不到,则返回string::npos
。pos
可以省略,默认从位置0
开始。string s = "Hello, World!"; size_t pos = s.find("World"); // 7
-
s.replace(pos, len, str)
:在字符串s
中,从第pos
个位置开始,替换len
个字符为字符串str
,并返回修改后的字符串。string s = "Hello, World!"; s.replace(7, 5, "Universe"); // "Hello, Universe!"
-
s.erase(pos, len)
:在字符串s
中,从第pos
个位置开始,删除len
个字符,并返回修改后的字符串。string s = "Hello, World!"; s.erase(5, 7); // "Hello!"
-
s.c_str()
:获取字符串s
的C风格字符串指针(const char*
),用于与C语言兼容的函数接口。string s = "Hello, World!"; const char* cstr = s.c_str(); // "Hello, World!"