在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;
}