public void AAAAA(String thetext, int numb)
{
List<String> items = new LinkedList<String>(Arrays.asList(thetext.split(" "))); //split string to individual characters
int len = items.size(); //get size of string
for(int j = 0; j < len; j++){ // loop through list
if(j % width == 0){
items.add(numb, "\n");
}
}
System.out.println(items);
}
}
文本示例:“你好,我叫鲍勃,我喜欢爱可爱的肥狗”
如果numb
为3,则预期输出;
hello my name
is bob i
like to pet
cute fat dogs
答案 0 :(得分:0)
尝试结合使用模和附加到新列表中
String thetext = "hello my name is bob i like to pet cute fat dogs";
int splitOn = 3;
String arr [] = thetext.split(" ");
List<String> newList = new ArrayList<String>();
StringBuilder buf = new StringBuilder();
for (int x = 0; x < arr.length; x++) {
buf.append(arr[x]).append(" ");
if ((x + 1) % splitOn == 0) {
newList.add(buf.toString());
newList.add(" ");
buf = new StringBuilder();
}
}
newList.add(buf.toString());
for (String line : newList) {
System.out.println(line);
}
答案 1 :(得分:0)
如果您只想每3个单词打印一个换行符(对于numb = 3),则可以修改方法以打印出列表的内容,并在那里使用模数逻辑。无需添加或修改列表。