[英]Java - Adding a new line every n characters without breaking apart the word
所以我一直試圖讓用戶輸入的字符串每 n 個字符有一個換行符。 我發現基本上是我寫的,我對 Java 很陌生(Python 有一個 function to.fill,但我無法在 Java 中解決這個問題)並且似乎無法讓我的字符串不把單詞分開。 我將程序設置為每 10 個字符“\n”,但它會在中間打斷一些單詞......如果它不符合 10 個字符的限制,我希望它接受該單詞並將其移動到下一行。
import java.util.Scanner;
public class Wrap {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter your text: ");
String newString = scan.nextLine();
newString = newString.replaceAll(".{10}", "$0\n");
System.out.println(newString);
/** 第二種方法,還是截斷單詞...
StringBuilder builtString = new StringBuilder();
int i = 0;
while ((i= builtString.indexOf(newString, i + 10)) != -1) {
builtString.replace(i, i+1, "\n");
}
System.out.println(builtString);
*/
System.out.println(newString);
}
}
單詞被分開了:(
Output:
This is a
test and i
t doesnt s
eem to be
working pr
operly.
In Python I got this output which was what I wanted, but Java doesn't seem to have a textwrap function that's "easy" like Python's or at least I haven't figured it out yet. 所需 Output
public static void main(String[] args) {
String text = "This is a test and it doesnt seem to be working properly.";
String[] works = text.split(" "); // get list of works
StringBuilder line = new StringBuilder();
StringBuilder result = new StringBuilder();
for (String work : works) {
if (line.length() + work.length() > 10) { //add line to result if it full
result.append(line).append("\n");
line = new StringBuilder(); //reset line is empty
}
line.append(work).append(" ");
}
result.append(line);
System.out.println(result.toString());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.