[英]Get character that is right after a specific word in a string?
我有一个文本字符串和一个需要在该字符串中找到的特定单词。 一旦找到字符串中该单词的下一个出现位置,就需要以某种方式找到该单词之后的字符。 我尝试使用扫描仪,但是它不包含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();
}
提前致谢!
使用String#indexOf
方法确定单词是否在字符串中。 如果是这样,请使用charAt
方法,使用返回的索引,添加单词的长度,并将该结果用作字符串的索引。 请注意,您不会用尽字符串的结尾。
尝试使用String
类提供的IndexOf
方法。
int idx = str.IndexOf(seed);
return str.charAt(idx + seed.Length);
显然,这没有做任何检查,因为您的字符串可能会在最后发现,并且索引将超出范围。 此外,如果字符串不匹配,将为索引返回-1
。
如果您的文本是“ Hello World”,并且想要查找单词“ Hell”之后的内容,则可以使用正则表达式,例如:“ Hell(。)”
然后,第一个捕获组将为“ o”,这就是您想要的。
如果您不了解RE,请阅读以下内容: http : //docs.oracle.com/javase/tutorial/essential/regex/
然后针对捕获组: http : //docs.oracle.com/javase/tutorial/essential/regex/groups.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.