li-heng 2023-04-04 22:32 采纳率: 81.5%
浏览 91
已结题

C++ 字符串去掉首位空格、回车、换行、制表符号

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。

  • 写回答

3条回答 默认 最新

  • 「已注销」 2023-04-04 22:39
    关注

    引用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 文件。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 4月12日
  • 已采纳回答 4月4日
  • 修改了问题 4月4日
  • 创建了问题 4月4日