在java中是否有一种方法可以扫描字符串并在重复的关键字索引之前添加行

在java中是否有一种方法可以扫描字符串并在重复的关键字索引之前添加行,java,string,function,position,Java,String,Function,Position,`女人穿着黑色的衣服,太阳是黄色的,苹果是圆形的,猫喝牛奶 我希望输出是一个字符串,但如下所示 The woman wears black dress the sun is yellow the apple has circle shape the cat drinks milk 每句话用不同的一行 我试着用那个代码给出关键字的索引,但不知道下一步该去哪里,那个代码会打印关键字的所有索引 public static void main(String args[]) throws Excepti

`女人穿着黑色的衣服,太阳是黄色的,苹果是圆形的,猫喝牛奶

我希望输出是一个字符串,但如下所示

The woman wears black dress
the sun is yellow
the apple has circle shape
the cat drinks milk
每句话用不同的一行

我试着用那个代码给出关键字的索引,但不知道下一步该去哪里,那个代码会打印关键字的所有索引

public static void main(String args[]) throws Exception{
    InputStream is = new FileInputStream("C:\\Users\\HP\\Documents\\output3.txt");
    BufferedReader buf = new BufferedReader(new InputStreamReader(is));
    String line = buf.readLine();
    StringBuilder sb = new StringBuilder(); 
    while(line != null){ 
      sb.append(line).append("\n"); 
      line = buf.readLine(); 
    }
    String fileAsString = sb.toString();
    System.out.println("Contents : " + fileAsString);
    String keyword="the";
    int index = fileAsString.indexOf(keyword);
    while (index >=0) {
        int sum=0;
        System.out.println("Index : "+index);}

您可以分两步完成此操作

  • 根据重复的关键字拆分句子
  • 用新行字符连接关键字上的字符串数组
  • 您可以按照下面的代码进行操作

    public String splitSentenceOnRepeatedKyword(String input,String keyword) {
       
     // Split sentence on keyword
        String [] res = input.toLowerCase().split(keyword);
        
     // join array of String on keyword with new line
        return String.join("\n the",res);
    }
    

    可以使用正则表达式拆分字符串。使用流的一行程序:

    String str = "The woman wears black dress the sun is yellow the apple has circle shape the cat drinks milk";
        
    String splited = Pattern.compile("(?=(?i)\\bThe\\b)")
                            .splitAsStream(str)
                            .collect(Collectors.joining(System.lineSeparator()));
    
    System.out.println(splited);
    

    但是
    is
    在你的文本中也出现过很多次,为什么不在下一行的开头移动呢?这只是一个示例数据,实际数据只重复了一个单词,所以你的示例是错误的。请更正它以匹配您所面临问题的描述。除了@Pshemo所建议的内容外,还可以发布您尝试过的任何代码。谢谢您的建议,我现在编辑了它