-3

I need to extract the substring "is a random te" but I only know the word random and the margins 5(characters) for left and 3 for right.

This is a random text

How can I do that?

Student
  • 47
  • 1
  • 7
  • 1
    Str.substring(5, Str.length()-2) ; – Saurav Sahu Sep 12 '16 at 03:14
  • 1
    Possible duplicate of [Java: Getting a substring from a string starting after a particular character](http://stackoverflow.com/questions/14316487/java-getting-a-substring-from-a-string-starting-after-a-particular-character) – Ishita Sinha Sep 12 '16 at 04:58

2 Answers2

1
  1. Look for the index of the target word
  2. Subtract the left margin to get the initial index
  3. Add the length of the target word plus the right margin to get the end index
  4. Extract the substring between the initial index and the end index, inclusive.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

You can use substring like this

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

Output

is a random te
Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424
  • This works only for the particular sentence. I need to work for every sentence that include the string "is a random te" – Student Sep 12 '16 at 03:46