alexanders916 alexanders916 - 7 months ago 13
Java Question

Search for CharSequences between two CharSeqeunces (Java)

first of all I want to say, that I'm a noobie in Java. (Sorry if the answer is that easy).
I have a String, which contains following text:

String htmlContent = "DienstagfälltMittwochfällt";


Now I have 3 CharSequences:

CharSequence dt = "Dienstag";
CharSequence mt = "Mittwoch";
CharSequence keyword = "fällt";


I want search

fällt


between the other 2 CharSequences. I shouldn't find

fällt


after the CharSequence

Mittwoch


Is there a method or something else? And when not, how I can realize my idea?
An example wouldn't be bad :).

My code now:

import java.io.*;
import java.net.*;

public class TextScanner {

public static void main (String[] args) throws Exception{
URL url = new URL("http://mpg-vertretungsplan.de/w/18/w00023.htm");
InputStream is = (InputStream) url.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
StringBuffer sb = new StringBuffer();
while((line = br.readLine()) != null){
sb.append(line);
}
String htmlContent = sb.toString();
System.out.println(htmlContent);
CharSequence dt="Dienstag";
CharSequence mt="Mittwoch";
CharSequence keyword="fällt";
boolean found = htmlContent.contains(keyword);
if(found==true){
System.out.println("Es gibt eine Fehlstunde!");
}else{
System.out.println("Es gibt keine Fehlstunde!");
}

}
}


I want that the answer is also false, if

keyword


is after

mt


in the string:

String htmlContent2 = "DienstagMittwochfällt";

Answer

You could use String.indexOf(String substr) to get the position of the two delimiters in the String, then use String.substring(int beginIndex, int endIndex) to get what's between them.

Note that String.indexOf(String substr) returns the starting position of the substring, so to compute the beginIndex you'll need to add the first delimiter's length.
Also, those methods work on Strings rather than CharSequence, so you'll have to convert them with .toString().

Once you've retrieved that substring, use .contains(CharSequence substr) as you currently do to check if it contains the searched CharSequence.

You can see it in action here.

Comments