简体   繁体   English

在 C++ 中按换行符拆分字符串

[英]Splitting strings by newline character in C++

If I have two tables stored in std::string variables, how could I display them side-by-side?如果我有两个表存储在std::string变量中,我如何并排显示它们? In particular...特别是...

I have std::string table1 which contains the following:我有std::string table1 ,其中包含以下内容:

 X | Y
-------
 2 | 3
 1 | 3
 5 | 2

I have std::string table2 which contains the following:我有std::string table2包含以下内容:

 X | Y
-------
 1 | 6
 1 | 1
 2 | 1
 3 | 5
 2 | 3

I need to modify them (or really just print them to standard output) so that the following appears:我需要修改它们(或者真的只是将它们打印到标准输出),以便出现以下内容:

 X | Y    X | Y
-------  -------
 2 | 3    1 | 6
 1 | 3    1 | 1
 5 | 2    2 | 1
          3 | 5
          2 | 3

In other words, I have two tables stored in std::string variables with newline characters separating the rows.换句话说,我有两个表存储在std::string变量中,换行符分隔行。

I would like to print them to screen (using std::cout ) so that the tables appear side-by-side, vertically aligned at the top.我想将它们打印到屏幕上(使用std::cout ),以便表格并排显示,在顶部垂直对齐。 How could I do this?我怎么能这样做?

For example, if I could do something like std::cout << table1.nextToken('\\n') where nextToken('\\n') gives the next token and tokens are separated by the '\\n' character, then I could devise a method to cycle through all tokens, and once all of table1 tokens are used, I could then simply print space characters so that the remaining tokens of table2 are properly horizontally aligned.例如,如果我可以执行类似std::cout << table1.nextToken('\\n') ,其中nextToken('\\n')给出下一个标记,并且标记由'\\n'字符分隔,那么我可以设计一种方法来循环遍历所有标记,一旦使用了所有table1标记,我就可以简单地打印空格字符,以便table2的其余标记正确水平对齐。 But, such a nextToken(std::string) function does not exist --- I don't know of it, at least.但是,这样的nextToken(std::string)函数不存在——至少我不知道。

Key words: istringstream, getline关键词:istringstream、getline

Implementaion:实施:

#include <iostream>
#include <sstream>
int main()
{
    std::string table1 = 
        " X | Y\n"
        "-------\n"
        " 2 | 3\n"
        " 1 | 3\n"
        " 5 | 2\n";
    std::string table2 = 
        " X | Y\n"
        "-------\n"
        " 1 | 6\n"
        " 1 | 1\n"
        " 2 | 1\n"
        " 3 | 5\n"
        " 2 | 3\n";

    std::istringstream streamTable1(table1);
    std::istringstream streamTable2(table2);
    while (!streamTable1.eof() || !streamTable2.eof())
    {
        std::string s1;
        getline(streamTable1, s1);
        while (s1.size() < 9)
            s1 += " ";
        std::string s2;
        getline(streamTable2, s2);
        std::cout << s1 << s2 << std::endl;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM