如何在列表中每第 n 个位置添加新行?

我试图按照标题所说的那样做,但我目前得到了错误的输出,我在这段代码中做错了什么?


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


慕桂英4014372
浏览 115回答 2
2回答

千巷猫影

如果您只想为每 3 个单词打印一个换行符(对于 numb = 3),您可以修改您的方法以打印出列表的内容并在那里使用您的模逻辑。无需添加或修改列表。

SMILET

尝试结合使用 modula 和附加到新列表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++) {&nbsp; &nbsp; buf.append(arr[x]).append(" ");&nbsp; &nbsp; if ((x + 1) % splitOn == 0) {&nbsp; &nbsp; &nbsp; &nbsp; newList.add(buf.toString());&nbsp; &nbsp; &nbsp; &nbsp; newList.add(" ");&nbsp; &nbsp; &nbsp; &nbsp; buf = new StringBuilder();&nbsp; &nbsp; }}newList.add(buf.toString());for (String line : newList) {&nbsp; &nbsp; System.out.println(line);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java