问题
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