在C++中,string是一个标准库类,用于表示和操作字符串。可以通过包含< string >头文件来使用string类。下面是string类的一些常用用法及示例代码:
#include <string>
#include <iostream>
int main() {
std::string str;
std::cout << str << std::endl; // 输出空字符串
return 0;
}
#include <string>
#include <iostream>
int main() {
std::string str = "Hello, World!";
std::cout << str << std::endl; // 输出 Hello, World!
return 0;
}
#include <string>
#include <iostream>
int main() {
std::string str1 = "Hello, ";
std::string str2 = "World!";
std::string result = str1 + str2;
std::cout << result << std::endl; // 输出 Hello, World!
return 0;
}
#include <string>
#include <iostream>
int main() {
std::string str = "Hello, World!";
std::cout << "String length: " << str.length() << std::endl; // 输出字符串长度
return 0;
}
#include <string>
#include <iostream>
int main() {
std::string str = "Hello, World!";
char firstChar = str[0];
std::cout << "First character: " << firstChar << std::endl; // 输出第一个字符
return 0;
}
#include <string>
#include <iostream>
int main() {
std::string str = "Hello, World!";
std::size_t found = str.find("World");
if (found != std::string::npos) {
std::cout << "Substring found at position: " << found << std::endl;
} else {
std::cout << "Substring not found" << std::endl;
}
return 0;
}