下面是一个例子
String str = 'Java是一种高级编程语言,最初由Sun Microsystems开发,1995年发布。
尝试根据定义的索引值来拆分字符串,但如果该索引位于单词的中间,则在单词后面将其拆分。
因此,如果索引是31,那么这个句子实际上会像这样分开(每行有31个字符长的)
Java is a high-level programmin
g language originally developed
by Sun Microsystems and release
d in 1995注意“编程”和“发布”两个词是如何分开的。如果索引处的字符不是空格,我想将其移到下一个空格,然后拆分字符串。例如:
Java is a high-level programming
language originally developed by
Sun Microsystems and released in
1995在上面的插图中,没有一个单词被分割(每行至少有31个字符长)。
发布于 2022-01-26 21:51:37
这里有一条路。不涉及明显的循环。
int mid = str.length()/2;
int indexBeyondMid = str.indexOf(' ',mid);
int indexBeforeMid = str.substring(0,mid).lastIndexOf(' ');
int splitPoint = mid - indexBeforeMid < indexBeyondMid - mid
? indexBeforeMid
: indexBeyondMid;
String firstHalf = str.substring(0,splitPoint);
String secondHalf = str.substring(splitPoint+1); // ignores leading space.
System.out.println(firstHalf);
System.out.println(secondHalf);上述各点将尽可能均匀地分配。如果您想在中间点之后的第一个空间上拆分,那么只需要在indexBeyondMid上拆分,然后忘记剩下的部分。
如果您希望尽可能地将一行拆分为指定的线宽,您可以这样做。
int lineWidth = 19;
while (!str.isBlank()) {
lineWidth = lineWidth > str.length() ? str.length() : lineWidth;
int indexBeyondMid = str.indexOf(' ',lineWidth);
int indexBeforeMid = str.substring(0,lineWidth).lastIndexOf(' ');
int splitPoint = lineWidth - indexBeforeMid < indexBeyondMid - lineWidth
? indexBeforeMid
: indexBeyondMid;
if (splitPoint < 0) {
System.out.println(str);
break;
}
System.out.println(str.substring(0, splitPoint));
str = str.substring(splitPoint+1);
}版画
Hey I am string that
will be split but
remember i will not
be cut in the middle
of the word发布于 2022-01-26 21:23:41
这是一个简单的解决方案:
import java.util.*;
public class Main
{
public static String[] splitBy(String text, int index)
{
int charIn = 0;
String[] defaultArray = new String[2];
for(charIn = index; charIn < text.length(); charIn++)
{
if(text.charAt(charIn) == ' ')
{
defaultArray[0] = text.substring(0, charIn);
defaultArray[1] = text.substring(charIn, text.length() - 1);
return defaultArray;
}
}
return defaultArray;
}
public static void main(String[] args)
{
String text = "This is a nice text"; // Your text
int index = 10; // Index to split
System.out.println(splitBy(text, index)[0]); // Print first part of the splitted
System.out.println(splitBy(text, index)[1]); // Print part 2
}
}https://stackoverflow.com/questions/70870257
复制相似问题