首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我有一个字符串包含类似72次重复的单词,我想将文本拆分为许多字符串,其中包含该单词之间的子字符串

我有一个字符串包含类似72次重复的单词,我想将文本拆分为许多字符串,其中包含该单词之间的子字符串
EN

Stack Overflow用户
提问于 2020-07-03 02:57:44
回答 2查看 50关注 0票数 0

我有一个字符串,其中包含一个重复出现的单词72次,我想将文本分成多个子字符串,每个子字符串包含该单词第一次出现和第二次出现之间的字符串,然后第二个子字符串包含第二次出现和第三次出现之间的字符串,依此类推,直到最后一个出现为止//我的样本数据如(黄太阳、绿树、大房子)//认为是重复出现的单词

代码语言:javascript
复制
public class wordOutput {
   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="AGE";
        int index = fileAsString.indexOf(keyword);
        while (index >=0){
            System.out.println("Index : "+index);
            index = fileAsString.indexOf(keyword, index+keyword.length())   ;
         
           
    
          
        
        } int last=fileAsString.length();
        
          System.out.println("last " +last);
         
        }
   }
}
EN

回答 2

Stack Overflow用户

发布于 2020-07-03 03:14:50

您可以简单地使用String[] arr = String.split("repeatedWordHere"),也可以忽略数组的第一个和最后一个元素

票数 1
EN

Stack Overflow用户

发布于 2020-07-03 03:30:14

如果您已经给出了示例数据,那就更好了,但是,根据您的语句,您可以使用可用于String对象的split(String regex)方法。

代码语言:javascript
复制
 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="AGE";
          printDelimitedValues(fileAsString, keyword); // calling method to split here
         
        }
 
 public static void printDelimitedValues(String str , String delimiter) {
        
        String strArr[] = str.split(delimiter);
        for(String substr:strArr) {
            System.out.println(substr);
        }
        
    }

因此,如果样本数据是这样的:,敏捷棕色狐狸年龄,关键字是年龄,输出将是:

敏捷的棕色狐狸

敏捷的棕色狐狸

敏捷的棕色狐狸

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62703282

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档