java获取字符串中特定单词后面的字符?
我有一个文本字符串和一个我需要在字符串中找到的特定单词。一旦我在字符串中找到下一个出现的单词,我需要以某种方式找到该单词后面的字符。我尝试使用scanner,但它不包含nextChar()方法,类似的东西可以满足我的目的。我还能尝试什么?这是我的代码,但它不符合我的要求
public void storeChar(String str) //used to get the char after the seed and store it in the arraylist of chars
{
Scanner sc = new Scanner(str);
seed = wrdSd.getSeed();
while(sc.hasNext()) //while there are words left to read
{
String next = sc.next();
if(next.equals(seed)) //if the next word of the scanner = the seed
{
ch = sc.next().charAt(0); //gets char at index 0 of the next word
singleChar.add(ch); //adds the char to the char arraylist
}
}
sc.close();
}
提前谢谢
# 1 楼答案
如果你的文本是“Hello World”,你想找到“Hell”一词后面的内容,你可以使用正则表达式,比如: “见鬼()”
然后第一个抓捕小组将是“o”,这就是你想要的
如果你不了解RE,请阅读以下内容: http://docs.oracle.com/javase/tutorial/essential/regex/
然后是针对捕获组的: http://docs.oracle.com/javase/tutorial/essential/regex/groups.html
# 2 楼答案
使用^{} 方法确定单词是否在字符串中。如果是,则使用返回的索引,添加单词的长度,并使用
charAt
方法将该结果用作字符串的索引。小心不要跑过头