如何打印“对齐”文本在控制台中使用现代C ++ [英] How to print "justified" text in the console using modern C++

查看:481
本文介绍了如何打印“对齐”文本在控制台中使用现代C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何格式化文本对齐,使其对齐到给定宽度的左侧和右侧?

How can I format text "justified" so it aligns to the left and right side for a given width?

int main()
{
    printJustified("A long text with many words. "
        "A long text with many words. "
        "A long text with many words. "
        "A long text with many words. "
        "A long text with many words.");
}

预期输出:

A  long text with many words. A long text with
many  words.  A  long  text with many words. A
long text with many words.


推荐答案

一个简单的例子如何解决这个问题是:

A simple example how to solve this problem is this:

#include <iostream>
#include <sstream>
#include <list>

const int pageWidth = 78;
typedef std::list<std::string> WordList;

WordList splitTextIntoWords( const std::string &text )
{
    WordList words;
    std::istringstream in(text);
    std::copy(std::istream_iterator<std::string>(in),
              std::istream_iterator<std::string>(),
              std::back_inserter(words));
    return words;
}

void justifyLine( std::string line )
{
    size_t pos = line.find_first_of(' ');
    if (pos != std::string::npos) {
        while (line.size() < pageWidth) {
            pos = line.find_first_not_of(' ', pos);
            line.insert(pos, " ");
            pos = line.find_first_of(' ', pos+1);
            if (pos == std::string::npos) {
                pos = line.find_first_of(' ');
            }
        }
    }
    std::cout << line << std::endl;
}

void justifyText( const std::string &text )
{
    WordList words = splitTextIntoWords(text);

    std::string line;
    for (const std::string& word : words) {
        if (line.size() + word.size() + 1 > pageWidth) { // next word doesn't fit into the line.
            justifyLine(line);
            line.clear();
            line = word;
        } else {
            if (!line.empty()) {
                line.append(" ");
            }
            line.append(word);
        }
    }
    std::cout << line << std::endl;
}

int main()
{
    justifyText("This small code sample will format a paragraph which "
        "is passed to the justify text function to fill the "
        "selected page with and insert breaks where necessary. "
        "It is working like the justify formatting in text "
        "processors.");
    return 0;
}

它的工作原理如下:


  • 首先将文本拆分为单词。

  • 将单词添加到各行,直到该单词无法再接受更多单词。

  • 对于每一行,在单词之间添加空格,直到行与所请求的宽度匹配。

这篇关于如何打印“对齐”文本在控制台中使用现代C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆