如何将一个长字符串按单词拆分为 2 个字符串,但不在单词中间[java]
How to split a long string in 2 strings by words, but not in the middle of a word[java]
如果我的字符串太长,我想把它分成2个子字符串显示。
这是我使用的代码:
if(newQuestion.length() > 35){
String first_part = newQuestion.substring(0,newQuestion.length()/2);
String second_part = newQuestion.substring(newQuestion.length()/2);
question1.setText(first_part + "\n" + second_part);
}
else{question1.setText(newQuestion + "");}
这导致:
Bronze age settlemen
ts in northern India.
如果字符串总长度 > 35,但不拆分实际单词,我该如何拆分它,因为它不好?
分裂于 space。然后将单词添加到第一个字符串,直到字符串长度为 35 个字符,然后将其余单词添加到 2. 字符串。但听起来视图 question1
应该能够自己处理这个问题?
String newQuestion = "Bronze age settlements in northern India.";
String[] words = newQuestion.split(" ");
String line1 = "";
String line2 = "";
int size = 0;
for(int i = 0; (line1.length() + words[i].length()) < 25; i++) {
size++;
line1 += words[i] + " ";
}
for(int j = size; j < words.length; j++) {
line2 += words[j] + " ";
}
System.out.println(line1);
System.out.println(line2);
如果我的字符串太长,我想把它分成2个子字符串显示。
这是我使用的代码:
if(newQuestion.length() > 35){
String first_part = newQuestion.substring(0,newQuestion.length()/2);
String second_part = newQuestion.substring(newQuestion.length()/2);
question1.setText(first_part + "\n" + second_part);
}
else{question1.setText(newQuestion + "");}
这导致:
Bronze age settlemen
ts in northern India.
如果字符串总长度 > 35,但不拆分实际单词,我该如何拆分它,因为它不好?
分裂于 space。然后将单词添加到第一个字符串,直到字符串长度为 35 个字符,然后将其余单词添加到 2. 字符串。但听起来视图 question1
应该能够自己处理这个问题?
String newQuestion = "Bronze age settlements in northern India.";
String[] words = newQuestion.split(" ");
String line1 = "";
String line2 = "";
int size = 0;
for(int i = 0; (line1.length() + words[i].length()) < 25; i++) {
size++;
line1 += words[i] + " ";
}
for(int j = size; j < words.length; j++) {
line2 += words[j] + " ";
}
System.out.println(line1);
System.out.println(line2);