substr
- 功能:返回一个子字符串,该子字符串是从原字符串指定位置开始,长度为指定值的部分。
- 用法:
string substr (size_t pos = 0, size_t len = npos) const;
,pos
是起始位置(默认为0),len
是子字符串长度(默认为直到字符串末尾)。
- 代码示例:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::string sub = str.substr(7, 5);
std::cout << sub << std::endl;
return 0;
}
find
- 功能:查找字符串中首次出现指定子字符串或字符的位置。
- 用法:
size_t find (const string& str, size_t pos = 0) const;
查找子字符串str
,从位置pos
开始。
size_t find (const char* s, size_t pos = 0) const;
查找以\0
结尾的字符串s
,从位置pos
开始。
size_t find (char c, size_t pos = 0) const;
查找字符c
,从位置pos
开始。
- 代码示例:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
size_t pos = str.find("World");
if (pos != std::string::npos) {
std::cout << "Found at position: " << pos << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
replace
- 功能:替换字符串中指定范围内的字符为新的字符串。
- 用法:
string& replace (size_t pos, size_t len, const string& str);
从位置pos
开始,长度为len
的部分替换为str
。
string& replace (size_t pos, size_t len, const char* s);
从位置pos
开始,长度为len
的部分替换为以\0
结尾的字符串s
。
- 代码示例:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
str.replace(7, 5, "C++");
std::cout << str << std::endl;
return 0;
}
append
- 功能:在字符串末尾添加内容。
- 用法:
string& append (const string& str);
添加字符串str
。
string& append (const char* s);
添加以\0
结尾的字符串s
。
- 代码示例:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello";
str.append(", World!");
std::cout << str << std::endl;
return 0;
}
length
/ size
- 功能:返回字符串的长度(字符个数)。
- 用法:
size_t length() const;
和 size_t size() const;
二者功能相同。
- 代码示例:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::cout << "Length: " << str.length() << std::endl;
std::cout << "Size: " << str.size() << std::endl;
return 0;
}