[英]How can I check and display the word between two other specific words?
The user will enter a string value that will contain two “bread” word. 用户将输入一个包含两个“面包”字的字符串值。 My program will printout the string that is between the first and last appearance of "bread" in the given string, or print “There is no sandwich!” if there are not two pieces of bread. 我的程序将打印出给定字符串中“面包”的第一个和最后一个外观之间的字符串,或者如果没有两块面包,则打印“没有三明治!”。 For example, for the input "breadlolbread", the output should be "lol". 例如,对于输入“ breadlolbread”,输出应为“ lol”。
String a = "There is no sandwich!";
for (int i =0;i<len-3;i++) {
if ((s.charAt(i)== 'b')&&(s.charAt(i+1)== 'r')&&(s.charAt(i+2)== 'e')&&(s.charAt(i+3)== 'a')&&(s.charAt(i+4)== 'd')) {
}
}
You can do this in two various ways. 您可以通过两种方法来完成此操作。 First one is to create a regular expression that will match the whole sentence ie two words provided by the user with the word between them. 第一个是创建一个正则表达式,该表达式将匹配整个句子,即用户提供的两个单词,其中两个单词之间。
The other way is probably easier, You can use split()
method to split String into the separate words and then simply iterate over the whole array to find the words you are looking for. 另一种方法可能更简单,您可以使用split()
方法将String拆分为单独的单词,然后简单地遍历整个数组以查找所需的单词。 The example would be : 示例为:
String userWord = "bread";
String word = "There are bread various bread breeds of dogs";
String[] wordSplit = word.split("");
for(int i = 0; i < wordSplit.length-2; i++) {
if(wordSplit[i].equals(userWord) && wordSplit[i+2].equals(userWord)) {
System.out.println(wordSplit[i+1]);
}
}
You could do something like: 您可以执行以下操作:
public static void main(String[] args) {
String text = "There are two bread which are very cool bread.";
String bread = "bread";
//make a new string by taking everything from first index of bread string+length of a bread string word and the last index of bread.
String inBEtween = text.substring(text.indexOf(bread)+bread.length(), text.lastIndexOf(bread));
//if the length inbetween trimmed of leading and tailing whitespace is greater than 0, print inBetween, otherwise print "No sandwich".
if (inBEtween.trim().length() > 0) {
System.out.println(inBEtween);
} else {
System.out.println("No sandwich.");
}
}
Of course, you could do this with regex too 当然,您也可以使用正则表达式
public static void main(String[] args) {
String text = "There are two bread bread.";
String pattern = "(?<=bread)(.*)(?=bread)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(text);
if (m.find()) {
System.out.println(m.group());
} else {
System.out.println("No sandwich");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.