在C++中, std::string 类有许多常用函数,以下是一些常见的:
1. length() 或 size() :返回字符串的长度(字符个数),二者功能相同。例如:
#include <iostream>
#include <string>
int main() {
std::string str = "hello";
std::cout << str.length() << std::endl;
std::cout << str.size() << std::endl;
return 0;
}
2. empty() :检查字符串是否为空,为空返回 true ,否则返回 false 。
#include <iostream>
#include <string>
int main() {
std::string str1 = "";
std::string str2 = "world";
std::cout << std::boolalpha << str1.empty() << std::endl;
std::cout << std::boolalpha << str2.empty() << std::endl;
return 0;
}
3. append() :在字符串末尾追加另一个字符串或字符序列。
#include <iostream>
#include <string>
int main() {
std::string str = "hello";
str.append(" world");
std::cout << str << std::endl;
return 0;
}
pop_back():删除字符串最后一个字符
str。pop_back():
4. substr() :返回字符串的子串。接受起始位置和长度作为参数。
cpp
#include <iostream>
#include <string>
int main() {
std::string str = "hello world";
std::string sub = str.substr(0, 5);
std::cout << sub << std::endl;
return 0;
}
5. find() :在字符串中查找指定子串或字符的位置,返回首次出现的位置索引,若未找到返回 std::string::npos 。
cpp
#include <iostream>
#include <string>
int main() {
std::string str = "hello world";
size_t pos = str.find("world");
if (pos != std::string::npos) {
std::cout << "子串位置: " << pos << std::endl;
}
return 0;
}
6. replace() :用新的子串替换字符串中指定的子串。
#include <iostream>
#include <string>
int main() {
std::string str = "hello world";
str.replace(6, 5, "C++");
std::cout << str << std::endl;
return 0;
}
7. c_str() :返回一个指向以空字符结尾的C风格字符串的指针。常用于与C语言函数接口。
#include <iostream>
#include <string>
#include <cstdio>
int main() {
std::string str = "hello";
const char* cstr = str.c_str();
printf("%s\n", cstr);
return 0;
}