string
A string in C++ is a sequence of characters. Strings are often used to process text data, such as user input, file content, etc. The C++ standard library provides a class called std::string for representing and processing strings.
1. Create and initialize C++ strings
In C++, strings can be created and initialized in several ways. Here are some commonly used methods:
(1) Direct assignment
std::string str = "Hello, World!";
(2) Use constructor
std::string str("Hello, World!");
(3) Use character array
char arr[] = "Hello, World!";
std::string str(arr);
(4) Use character pointer
const char* ptr = "Hello, World!";
std::string str(ptr);
2. Common operations on C++ strings
(1) Get the string length
Use size()
a function to get the length of a string.
std::string str = "Hello, World!";
int length = str.size(); // 长度为13
(2) Connection string
Two strings can be concatenated using +
operators or functions.append()
std::string str1 = "Hello";
std::string str2 = "World!";
std::string str3 = str1 + str2; // 结果为"HelloWorld!"
str3.append(str2); // 结果仍为"HelloWorld!"
(3) Access characters in a string
Characters in a string can be accessed using indexing operators []
or functions. at()
Note that the index starts from 0.
std::string str = "Hello, World!";
char firstChar = str[0]; // 结果为'H'
char secondChar = str.at(1); // 结果为'e',at()函数也可以用于访问字符串中的字符
(4) String comparison
Use operators such as ==
, , and to perform string comparisons.!=
<
>
std::string str1 = "Hello";
std::string str2 = "World";
if (str1 == str2) {
std::cout << "str1 and str2 are equal";
} else {
std::cout << "str1 and str2 are not equal";
}
3. C++ string processing functions
(1) String slicing: substr()
function
std::string str = "Hello, World!";
std::string subStr = str.substr(0, 5); // 结果为"Hello"
(2) String replacement: replace() function
std::string str = "Hello, World!";
str.replace(0, 5, "Hi"); // 结果为"Hi, World!"
(3) String splitting: find()
sum substr()
function
std::string str = "Hello, World!";
size_t pos = str.find(",");
std::string part1 = str.substr(0, pos); // 结果为"Hello"
std::string part2 = str.substr(pos + 1); // 结果为" World!"
4. Application of C++ strings in actual development
Strings are widely used in various scenarios in C++, such as user input processing, file operations, network communications, etc. Here are some examples:
(1) User input processing
Use strings to receive user input and process it accordingly.
#include <iostream>
#include <string>
int main() {
std::string input;
std::cout << "Enter your name: ";
std::getline(std::cin, input); // 读取一行输入到字符串中
std::cout << "Hello, " << input << "!"; // 输出问候语
return 0;
}
(2) File operations
Use strings to read or write file paths, file names, etc.
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::string filename = "example.txt"; // 文件名或路径
std::ofstream outfile(filename); // 创建输出文件流,打开文件进行写入操作
outfile << "Hello, World!"; // 写入内容到文件中
outfile.close(); // 关闭文件流,完成写入操作
return 0;
}
(3) Network communication
When processing network requests or responses, you often need to use strings to represent and process text data.
#include <iostream>
#include <string>
#include <curl/curl.h>
size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
std::stringbuf buf((char*)contents, size * nmemb);
std::string str = std::string(buf.data(), size * nmemb);
std::cout << str; // 输出接收到的文本数据
return size * nmemb;
}
int main() {
CURL *curl = curl_easy_init();
if (curl) {
std::string url = "http://example.com"; // 请求的URL
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_perform(curl); // 发送请求并接收响应
curl_easy_cleanup(curl);
}
return 0;
}
(4) String formatting
Use strings to organize and present data such as dates, times, currencies, and more.
#include <iostream>
#include <sstream>
#include <iomanip>
#include <ctime>
int main() {
std::time_t now = std::time(0); // 获取当前时间
std::tm* localTime = std::localtime(&now); // 转换为本地时间
std::ostringstream oss; // 创建输出字符串流
oss << "Today is " << std::put_time(localTime, "%A %B %d, %Y"); // 格式化输出时间字符串
std::string formattedDate = oss.str(); // 获取格式化后的字符串
std::cout << formattedDate; // 输出格式化后的日期字符串
return 0;
}