Java: methode om de positie van een overeenkomst in een String te krijgen?

String match = "hello";
String text = "0123456789hello0123456789";

int position = getPosition(match, text); // should be 10, is there such a method?
Oplossing

De familie van methoden die dit doen zijn:

Geeft als resultaat de index binnen deze string van het eerste (of laatste) voorkomen van de opgegeven substring [voorwaarts zoeken (of achterwaarts) beginnend bij de opgegeven index].


String text = "0123hello9012hello8901hello7890";
String word = "hello";

System.out.println(text.indexOf(word)); // prints "4"
System.out.println(text.lastIndexOf(word)); // prints "22"

// find all occurrences forward
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {
    System.out.println(i);
} // prints "4", "13", "22"

// find all occurrences backward
for (int i = text.length(); (i = text.lastIndexOf(word, i - 1)) != -1; i++) {
    System.out.println(i);
} // prints "22", "13", "4"
Commentaren (4)
text.indexOf(match);

Zie de String javadoc

Commentaren (0)

Gebruik string.indexOf om de beginindex te krijgen.

Commentaren (0)