我有一个字符串,其中包含一个重复出现的单词72次,我想将文本分成多个子字符串,每个子字符串包含该单词第一次出现和第二次出现之间的字符串,然后第二个子字符串包含第二次出现和第三次出现之间的字符串,依此类推,直到最后一个出现为止//我的样本数据如(黄太阳、绿树、大房子)//认为是重复出现的单词
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);
}
}
}发布于 2020-07-03 03:14:50
您可以简单地使用String[] arr = String.split("repeatedWordHere"),也可以忽略数组的第一个和最后一个元素
发布于 2020-07-03 03:30:14
如果您已经给出了示例数据,那就更好了,但是,根据您的语句,您可以使用可用于String对象的split(String regex)方法。
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);
}
}因此,如果样本数据是这样的:,敏捷棕色狐狸年龄,关键字是年龄,输出将是:
敏捷的棕色狐狸
敏捷的棕色狐狸
敏捷的棕色狐狸
https://stackoverflow.com/questions/62703282
复制相似问题