在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
類,可以方便地處理字符串操作。