在特定字符串后获取下一个字符/字符串
我想在字符串的给定段中获取下一个字符,因为每当该字被重复时,字符串的下一个字符应该打印,假设多达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));
您可以选择子字符串的开始和结束。试试这个:
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.
它是印刷的摇滚,我希望输出在给定的字符串中以“,让我们现在的Pr”打印为6个字符。 –
编辑它。这应该工作。你可以改变任何你想要的长度。 –
感谢您的检查,但它不应该打印rock ..它应该打印下一个字符后,也只有6个字符后。 –
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));
解决方案:假设只打印的字符不言,也计数空间
字符串例如=“你好人检查摇滚,让我们一起去视线岩现在打印最多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);
}
}
请在Luud评论中查看我想要的输出。它应该首先与“,让我们”,然后在同一行,“现在P”与空间..将一起看起来像“,让我们现在P”。 N.B:介意两个空格..现在总长度将是12。 –
获取下一个字符串/字一个特定的字符串(例如:岩石)后使用正则表达式
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: 让 现在 再次
什么是你期望的输出和输出做你得到? – IQV