2017-02-16 123 views
0

我想在字符串的給定段中獲取下一個字符,因爲每當該字被重複時,字符串的下一個字符應該打印,假設多達6個字符來獲取所需的字符串在給定的詞後。在特定字符串後獲取下一個字符/字符串

Ex。搖滾

我試過這個,但沒有得到所需的輸出。

String example = "Hi man check rock,let's go on together to the sight of rock now Print upto 6 char"; 
     System.out.println(example.substring(example.indexOf("rock") + 5)); 
+1

什麼是你期望的輸出和輸出做你得到? – IQV

回答

2

您可以選擇子字符串的開始和結束。試試這個:

int stringindex = example.indexOf("rock"); //Save the index to a variable so you don't have to call the indexOf method twice. 
int stringlength = "rock".length(); 
example.substring(stringindex + stringlength, stringindex + stringlength + 5); //Select next 5 characters from the index of rock. 
+0

它是印刷的搖滾,我希望輸出在給定的字符串中以「,讓我們現在的Pr」打印爲6個字符。 –

+0

編輯它。這應該工作。你可以改變任何你想要的長度。 –

+0

感謝您的檢查,但它不應該打印rock ..它應該打印下一個字符後,也只有6個字符後。 –

0
String example = "Hi man check rock,let's go on together to the sight of rock now Print upto 6 char"; 
System.out.println(example.substring(example.indexOf("rock")+4, example.indexOf("rock") + 11)); 
1

解決方案:假設只打印的字符不言,也計數空間

字符串例如=「你好人檢查搖滾,讓我們一起去視線巖現在打印最多6個字符「; (Str.lastIndexOf(「rock」)+「rock」.length(),Str.lastIndexOf(「rock」)+「rock」.length()+)。 6));

輸出:現在P(共6個字符,2個空格和4個字符)。

請讓我知道任何改進

更新:

請找到下面的代碼: 代碼最初捕獲的第一指標,並通過串其他OCCURENCES循環,並建立在循環裏結果字符串。

import java.io.*; 
public class Test { 

    public static void main(String args[]) { 
     String Str = "Hi man check rock,let's go on together to the sight of rock now Print upto 6 char"; 
    String keyword = "rock"; 
    String result=""; 

    int index = Str.indexOf(keyword); 
    while (index >=0){ 
     System.out.println("Index : "+index); 
     result+=Str.substring(index+keyword.length(),index+keyword.length()+6); 
     index = Str.indexOf(keyword, index+keyword.length()) ; 
    } 
    System.out.println(result); 
    } 
} 
+0

請在Luud評論中查看我想要的輸出。它應該首先與「,讓我們」,然後在同一行,「現在P」與空間..將一起看起來像「,讓我們現在P」。 N.B:介意兩個空格..現在總長度將是12。 –

0

獲取下一個字符串/字一個特定的字符串(例如:岩石)後使用正則表達式

String stringToSearch = "Hi man check rock,let's go on together to the sight of rock now rock again Print upto 6 char"; 
Pattern p1 = Pattern.compile("rock[,\\s][\\w]+"); 
Matcher m = p1.matcher(stringToSearch); 

Pattern p2 = Pattern.compile("[,\\s]"); 
while (m.find()) 
{ 
    String[] items = p2.split(m.group()); 
    if(items.length < 2) 
     break; 
    System.out.println(items[1]); 
} 

Otuput: 讓 現在 再次

相關問題