我正在閱讀包含整個段落的單獨文件的輸入。我將該段落中的單詞存儲在列表中。我的目標是從一個單獨的文件打印出一個完整的段落,每行不超過字符的字符限制。我通過使用列表迭代:每行字符數限制的打印行
for (String word: words)
我不知道如何編寫字符限制的代碼。我正在考慮使用StringBuffer
方法,但我不確定。有任何想法嗎?
我正在閱讀包含整個段落的單獨文件的輸入。我將該段落中的單詞存儲在列表中。我的目標是從一個單獨的文件打印出一個完整的段落,每行不超過字符的字符限制。我通過使用列表迭代:每行字符數限制的打印行
for (String word: words)
我不知道如何編寫字符限制的代碼。我正在考慮使用StringBuffer
方法,但我不確定。有任何想法嗎?
如果您在遇到它們時暫時保留單詞,那麼確實可以使用StringBuffer(或者如果您不關心線程安全性,請使用StringBuilder)。爲了強制使用字符限制,您可以計算添加字符在添加到緩衝區之前添加的字符數。一旦達到限制,請將緩衝區(輸入緩衝區/文件)刷新並重新開始。
這裏的東西快速和骯髒的我剛熟了起來:
import java.util.Scanner;
public class CharLimit {
static int LIMIT = 79;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuilder buffer = new StringBuilder(LIMIT);
while (sc.hasNextLine()) {
Scanner sc2 = new Scanner(sc.nextLine());
while (sc2.hasNext()) {
String nextWord = sc2.next();
if ((buffer.length() + nextWord.length() + 1) > LIMIT) {
// we would have exceeded the line limit; flush
buffer.append('\n');
System.out.print(buffer.toString());
buffer = new StringBuilder(nextWord);
}
else {
buffer.append((buffer.length() == 0 ? "" : " ") + nextWord);
}
}
}
if (buffer.length() > 0) {
System.out.print(buffer.toString() + "\n");
}
System.exit(0);
}
}
例子:
???:/tmp$ cat input
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.
???:/tmp$ java CharLimit < input
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
請注意,這並沒有考慮到一個「字」令牌是長於預先配置的限制。
您能否解釋.append方法在StringbBuffer類中做了什麼,因爲我已經閱讀了它的API文檔,但我仍不清楚。謝謝! – AayushK
對於StringBuilder,append()基本上是在函數調用參數(在我們的例子中是當前的「word」)中添加字符序列(String)。所以,如果你的緩衝區當前包含'「Hello」,那麼'buffer.append(「World!」);'會導致緩衝區現在包含'「Hello,World!」'。 – Santa
如何在這種情況下使用StringBuffer?說StringBuffer buffer = new StringBuffer(LIMIT); ? – AayushK
這似乎是你想要的:Java's BreakIterator
我個人的實現。代碼是舊的,從我的牛仔日,但它的作品。如你所願調整它。
private static final int LINE_LENGTH = 30;
private static final String SPACE = " ";
private static final String EMPTY_STRING = "";
/**
* Formats the given input text: <br />
* - Wraps text to lines of maximum <code>LINE_LENGTH</code> <br />
* - Adds newline characters at each line ending <br />
* - Returns as a string
*/
public static String getPreviewLines(final String input)
{
final StringTokenizer token = new StringTokenizer(input, SPACE);
final StringBuilder output = new StringBuilder(input.length());
int lineLen = 0;
while (token.hasMoreTokens())
{
final String word = token.nextToken() + SPACE;
if (lineLen + word.length() - 1 > LINE_LENGTH)
{
output.append(System.lineSeparator());
lineLen = 0;
}
output.append(word);
if (word.contains(System.lineSeparator()))
lineLen = word.replaceAll("\\s+", EMPTY_STRING).length(); //$NON-NLS-1$
else
lineLen += word.length();
}
return output.toString();
}
public static String lineSeparator = System.getProperty("line.separator");
public static int size = 10;
/**
* Main Method
* @param args
*/
public static void main(String[] args) {
String read = "enter any text here or read it from somewhere else the idea here is to split as many words you want and print it in the format you want";
String[] wordArray = read.trim().split(" ");
printBySize(size,wordArray);
}
private static void printBySize(int size, String[] wordArray) {
StringBuilder bld = new StringBuilder(size);
for(int i=0; i<wordArray.length;i++) {
String word = wordArray[i];
if ((bld.length() + word.length()) >= size) {
//if yes add a new line and create a new builder for the new line
bld.append(lineSeparator);
System.out.print(bld.toString());
bld = new StringBuilder(word);
}
else {
bld.append((bld.length() == 0 ? "" : " ") + word);
}
}
System.out.println(bld.toString());
}
什麼是行嗎?每個段落都是一條線還是有不同的映射?每當你遇到換行符/回車等行是一個行嗎? –