如果我有一个很长的文本字符串,我应该使用什么命令或方法才能在每行前面留下两个空格? 假设
String sentences = "The car is blue.
The sky is blue.
The house is blue."
输出应为
The car is blue.
The sky is blue.
The house is blue.
public static String indentByTwoSpaces(String text)
{
String[] words = text.split(" ");
}
答案 0 :(得分:2)
简单使用String.replace
System.out.println (" " + str.replaceAll("(\r\n|\n)", "\r\n "));
答案 1 :(得分:0)
1。使用正则表达式拆分行。
2. 使用循环进行迭代,通过格式化来打印内容 提供的字符串
注意 - 如果你需要在开始时将字符串与两个空格连接起来,那么只需将字符串拆分并连接两个空格<“”+ --->并返回
String splittedLines[] = text.split("\\r?\\n");
int index = 0;
while(index != splittedLines.length) {
String.format(" %s", splittedLines[index]);
index++;
}
答案 2 :(得分:0)
这完全取决于您的输入。
见下文,这将打印出您想要的输出,因为输入在句点后没有空格。如果有,你可以相应调整。
public class TestMain {
public static void main(String[] args) {
// notice how my text input doesnt have spaces after the periods
String text = "The car is blue.The sky is blue.The house is blue.";
StringBuilder sb = new StringBuilder();
String splittedLines[] = text.split("\\.");
int index = 0;
while(index != splittedLines.length) {
// if there are spaces after the periods, consider adjusting this
sb.append(" ");
sb.append(splittedLines[index]);
sb.append("\n");
index++;
}
System.out.print(sb);
}
}
答案 3 :(得分:0)
根据您的要求,您需要相应地分割线来识别句子。然而,根据给定的样本集合,我会注意到每个句子结束后的句号是完整的。因此,我建议使用(。)与正则表达式相应地分割线。然后你可以相应地格式化你的线,如下所示。
public class AddingSpaces {
public static void main(String[] args) {
// As shown below, you can have your own sentence even with or without spaces
String text = "The car is blue.The sky is blue.The house is blue.";
// Since there are multiple sentences, you can split it from full-stop
String splittedLines[] = text.split("\\.");
for (String line: splittedLines) {
StringBuilder sb = new StringBuilder();
sb.append(" ").append(line);
//Print the lines accordingly
System.out.println(sb);
}
}
}