C++ 字符串去掉首位空格、回车、换行、制表符号,兼容Linux和Windows、效率要高
我有一个文件text.txt ,各个字符之间使用 ”|“分割,但是每部分内容的前后(中间的空格等不处理)可能有空格、回车、换行、制表符号,且顺序和数量不定,求一个函数,能去掉每个|分割部分首位的多余符号,如下txt文件,
a | b
| c | d|e|f |
g
| h|i | j | k
|l m| n |o
最后得到一个vector,里面是 a、b、c、d、e、f、g、h、i、j、k、l m、n、o。
引用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 文件。
该回答引用于ChatGPT:
你可以使用C++的标准库中的字符串处理函数和算法来完成这个任务。以下是一个参考实现:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <vector>
void trim(std::string& s) {
// 去掉首位空格、回车、换行、制表符
s.erase(0, s.find_first_not_of(" \r\n\t"));
s.erase(s.find_last_not_of(" \r\n\t") + 1);
}
int main() {
std::ifstream fin("text.txt");
if (!fin.is_open()) {
std::cerr << "Failed to open file!";
return EXIT_FAILURE;
}
std::vector<std::string> result;
std::string line;
while (std::getline(fin, line, '|')) {
trim(line);
if (!line.empty()) {
result.push_back(line);
}
}
fin.close();
for (const auto& str : result) {
std::cout << str << std::endl;
}
return EXIT_SUCCESS;
}
这个程序从文件中读取每一行,然后对于每一行使用 '|'
分割字符串,并去掉分割后每部分的首尾多余字符,并将结果存储在一个 vector 中。最后,遍历这个 vector 就可以得到需要的结果。
注意,上述代码中用了 std::cerr
和 EXIT_FAILURE
来处理打开文件失败的情况,如果不需要可以去掉相关代码。另外,本代码可以在 Windows 和 Linux 等操作系统下运行。