2016-09-12 69 views
-3

我需要提取子字符串「是一個隨機te」,但我只知道單詞random和邊界5(字符)左邊和3右邊。如何獲得接近特定單詞的子字符串 - Java

This is a random text 

我該怎麼做?

+1

Str.substring(5,Str.length() - 2); –

+1

[Java:從特定字符開始的字符串中獲取子字符串]的可能重複(http://stackoverflow.com/questions/14316487/java-getting-a-substring-from-a-string-starting-after-特殊字符) –

回答

1
  1. 認準了目標詞
  2. 的指數減去左邊距獲取初始指數
  3. 添加目標詞的長度加上右邊距以得到最終的inde x
  4. 提取初始索引和結束索引之間的子串,包括(含)。
+0

非常感謝 – Student

0

您可以使用substring這樣

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 
+0

這隻適用於特定的句子。我需要爲包含字符串「是隨機te」的每個句子工作。 – Student

+0

@Student Ok。請再看一遍。我更新了代碼。 –

相關問題