有没有一种方法可以扫描字符串并在java

时间:2020-07-03 20:38:27

标签: 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 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);}

2 个答案:

答案 0 :(得分:0)

您可以分两步进行

  1. 用重复的关键字分隔句子
  2. 使用换行符将关键字的字符串数组连接起来

您可以按照以下代码

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);
}

答案 1 :(得分:0)

您可以使用正则表达式拆分字符串。一个使用流的班轮:

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);