C++ text full justification

若如初见. 提交于 2019-12-11 08:23:31

问题


I'm trying to do a program that full justifies/left and right justification a given string. I've already made the part where you know how many spaces needs to be between words in a string, but what I don't get is how to add or insert those spaces in between words.


回答1:


You could

count how many words are on each line

divide the number spaces by the number of words, now we know how many spaces need to be added to each word on average

for each word in the string, word += [number of spaces]




回答2:


A simple algorithm to do a spreading is

for (int i=0; i<num_words-1; i++) {
    int s0 = i * extra_spaces / (num_words - 1);
    int s1 = (i + 1) * extra_spaces / (num_words - 1);
    // add (s1 - s0) spaces between word[i] and word [i+1]
}



回答3:


Find the length of the string - sl

Count the number of space - n

Calculate the difference between l and the length of the line - ll

Calculate the width of each space - w

 w=(ll-sl)/n

Print the string one word at a time, advancing by w when you have a space.



来源:https://stackoverflow.com/questions/22183952/c-text-full-justification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!