如何获取靠近特定单词的子字符串-Java

如何获取靠近特定单词的子字符串-Java,java,string,Java,String,我需要提取子字符串“is a random te”,但我只知道单词random,左边的边距为5个字符,右边的边距为3个字符 This is a random text 我该怎么做呢?您可以像这样使用子字符串 class Main { public static void main(String args[]) { String string = "This is a random text"; String match = "is a random te

我需要提取子字符串“is a random te”,但我只知道单词random,左边的边距为5个字符,右边的边距为3个字符

This is a random text

我该怎么做呢?

您可以像这样使用
子字符串

class Main {
    public static void main(String args[]) {
        String string = "This is a random text";
        String match = "is a random te";
        int i1 = string.indexOf(match);
        int i2 = i1 + match.length();
        System.out.println(string.substring(i1, i2));
    }
}
输出

is a random te
  • 查找目标词的索引
  • 减去左边距得到初始索引
  • 将目标单词的长度加上右边距,得到结束索引
  • 提取初始索引和结束索引(包括)之间的子字符串

  • Str.substring(5,Str.length()-2);可能的重复只适用于特定的句子。我需要为每个句子,包括字符串“是一个随机的te”非常感谢你