Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: method to get position of a match in a String?

Tags:

java

string

match

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

int position = getPosition(match, text); // should be 10, is there such a method?
like image 576
hhh Avatar asked Sep 26 '22 15:09

hhh


People also ask

How do I find a character in a specific position in a string?

charAt(int position) method of String Class can be used to get the character at specific position in a String. Return type of charAt(int position) is char. Index or position is counted from 0 to length-1 characters.

Can you index a string Java?

You can get the character at a particular index within a string by invoking the charAt() accessor method. The index of the first character is 0, while the index of the last character is length()-1 . For example, the following code gets the character at index 9 in a string: String anotherPalindrome = "Niagara.

How do you find out which character is at the 3th position in a string Java?

To access the nth character of a string, we can use the built-in charAt() method in Java. The charAt() method takes the character index as an argument and return its value in the string.


2 Answers

The family of methods that does this are:

  • int indexOf(String str)
    • indexOf(String str, int fromIndex)
  • int lastIndexOf(String str)
    • lastIndexOf(String str, int fromIndex)

Returns the index within this string of the first (or last) occurrence of the specified substring [searching forward (or backward) starting at the specified 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"
like image 279
polygenelubricants Avatar answered Oct 20 '22 23:10

polygenelubricants


This works using regex.

String text = "I love you so much";
String wordToFind = "love";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(text);

while (match.find()) {
     System.out.println("Found love at index "+ match.start() +" - "+ (match.end()-1));
}

Output :

Found 'love' at index 2 - 5

General Rule :

  • Regex search left to right, and once the match characters has been used, it cannot be reused.
like image 49
Aldwane Viegan Avatar answered Oct 21 '22 00:10

Aldwane Viegan