引用new bing作答:
您可以使用以下代码来实现字符串去掉首尾空格、回车、换行、制表符号:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
void trim(std::string &str) {
str.erase(0, str.find_first_not_of(" \t\r\n"));
str.erase(str.find_last_not_of(" \t\r\n") + 1);
}
std::vector<std::string> split(const std::string &str, const std::string &delimiter = "|") {
std::vector<std::string> tokens;
size_t pos = 0, last_pos = 0;
while ((pos = str.find(delimiter, last_pos)) != std::string::npos) {
std::string token = str.substr(last_pos, pos - last_pos);
trim(token);
if (!token.empty()) {
tokens.push_back(token);
}
last_pos = pos + delimiter.size();
}
std::string last_token = str.substr(last_pos);
trim(last_token);
if (!last_token.empty()) {
tokens.push_back(last_token);
}
return tokens;
}
int main() {
std::string line;
std::vector<std::string> parts;
while (std::getline(std::cin, line)) {
std::vector<std::string> tokens = split(line);
parts.insert(parts.end(), tokens.begin(), tokens.end());
}
for (const std::string &part : parts) {
std::cout << part << std::endl;
}
return 0;
}
这个程序可以从标准输入读取多行文本,每行文本都会被分割成多个部分,每个部分都会被去掉首尾空格、回车、换行、制表符号,并存储到一个 vector 中,最后输出这个 vector 中的所有部分。你可以将 std::cin 替换成从文件读取输入来处理你的 text.txt 文件。