在C++中,字符串可以通过标准库中的std::string
类来定义和使用。以下是一些示例代码:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::cout << str << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello, ";
std::string str2 = "World!";
std::string result = str1 + str2;
std::cout << result << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::cout << "Length of string: " << str.length() << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
size_t found = str.find("World");
if (found != std::string::npos) {
str.replace(found, 5, "Universe");
}
std::cout << str << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello";
std::string str2 = "Hello";
if (str1 == str2) {
std::cout << "Strings are equal." << std::endl;
} else {
std::cout << "Strings are not equal." << std::endl;
}
return 0;
}
这些示例展示了如何定义、初始化、操作和比较字符串。通过使用std::string
类,可以方便地处理字符串操作。