String match = "hello";
String text = "0123456789hello0123456789";
int position = getPosition(match, text); // should be 10, is there such a method?
14 Answers
The family of methods that does this are:
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"

- 3
- 3

- 376,812
- 128
- 561
- 623
-
2lolz, just realised an assignment inside while-loop, then you post an assignment inside for-loop +1 – hhh Apr 11 '10 at 02:23
-
4@polygenelubricants - your "find all occurrences" examples are clever. But if was code-reviewing that, you would get a lecture about code maintainability. – Stephen C Apr 11 '10 at 03:23
-
3How would you write it? I'm honestly asking, because I haven't had a professional code review experience before. – polygenelubricants Apr 11 '10 at 03:27
-
1In find all occurrences, instead of i++, we can write i += word.length(). It should be slightly faster. – May Rest in Peace Feb 06 '18 at 08:02
-
First loop will fail to find all positions if matching one char. You don't need +1 in for loop second statement, because third statement does counting i++ try for String text = "0011100"; matching word char "1" it will print 2,4 not 2,3,4 – Strauteka Feb 03 '20 at 11:50
-
@polygenelubricants Hi, this kind of for loop is interesting to me. I'd like to know more about why the variable i = -1, and how i++ seems to make it scan to the end of the text, can it be explained more? I'm not refuting it, I know it works, I just want to understand the logic – Conor Jul 29 '20 at 15:16
-
It's inclusive of `fromIndex` for anyone wondering. – Siddhartha Feb 21 '21 at 23:06
-
Find all occurrences backward should be corrected as i--. not i++ – Kalpa-W Dec 10 '21 at 18:00
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.

- 484,302
- 314
- 1,365
- 1,393

- 491
- 4
- 3
-
30This works awesome, but for this sentence i got the output saying "I have a boyfriend" :-) – Gaurav Pangam Jan 17 '18 at 11:01
Finding a single index
As others have said, use text.indexOf(match)
to find a single match.
String text = "0123456789hello0123456789";
String match = "hello";
int position = text.indexOf(match); // position = 10
Finding multiple indexes
Because of @StephenC's comment about code maintainability and my own difficulty in understanding @polygenelubricants' answer, I wanted to find another way to get all the indexes of a match in a text string. The following code (which is modified from this answer) does so:
String text = "0123hello9012hello8901hello7890";
String match = "hello";
int index = text.indexOf(match);
int matchLength = match.length();
while (index >= 0) { // indexOf returns -1 if no match found
System.out.println(index);
index = text.indexOf(match, index + matchLength);
}

- 484,302
- 314
- 1,365
- 1,393
-
1
-
1@Fabio getPosition(match, text){ int match_position=text.indexOf(match); return match_position;} – Sayed Mar 25 '14 at 09:42
You can get all matches in a file simply by assigning inside while-loop, cool:
$ javac MatchTest.java
$ java MatchTest
1
16
31
46
$ cat MatchTest.java
import java.util.*;
import java.io.*;
public class MatchTest {
public static void main(String[] args){
String match = "hello";
String text = "hello0123456789hello0123456789hello1234567890hello3423243423232";
int i =0;
while((i=(text.indexOf(match,i)+1))>0)
System.out.println(i);
}
}

- 50,788
- 62
- 179
- 282
-
2The way you offset `i` by `+1` works, but in a rather roundabout way. As you've shown here, it reports the first `hello` at `i == 1`. It's much more consistent if you always use 0-based indexing. – polygenelubricants Apr 11 '10 at 02:26
-
1
import java.util.StringTokenizer;
public class Occourence {
public static void main(String[] args) {
String key=null,str ="my name noorus my name noorus";
int i=0,tot=0;
StringTokenizer st=new StringTokenizer(str," ");
while(st.hasMoreTokens())
{
tot=tot+1;
key = st.nextToken();
while((i=(str.indexOf(key,i)+1))>0)
{
System.out.println("position of "+key+" "+"is "+(i-1));
}
}
System.out.println("total words present in string "+tot);
}
}

- 13,289
- 5
- 51
- 78

- 1,342
- 3
- 15
- 33
-
1Can you explain why this works and what's going on in the guard of the inner loop? An explanation might be useful to a novice reader. – Paul Hicks Feb 09 '14 at 20:53
-
1int indexOf(String str, int fromIndex): Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If it does not occur, -1 is returned. Here the inner loop of while would be able to get all the occource of token(here specified by variable named as 'key'). – Noorus Khan Sep 15 '14 at 13:06
I have some big code but working nicely....
class strDemo
{
public static void main(String args[])
{
String s1=new String("The Ghost of The Arabean Sea");
String s2=new String ("The");
String s6=new String ("ehT");
StringBuffer s3;
StringBuffer s4=new StringBuffer(s1);
StringBuffer s5=new StringBuffer(s2);
char c1[]=new char[30];
char c2[]=new char[5];
char c3[]=new char[5];
s1.getChars(0,28,c1,0);
s2.getChars(0,3,c2,0);
s6.getChars(0,3,c3,0); s3=s4.reverse();
int pf=0,pl=0;
char c5[]=new char[30];
s3.getChars(0,28,c5,0);
for(int i=0;i<(s1.length()-s2.length());i++)
{
int j=0;
if(pf<=1)
{
while (c1[i+j]==c2[j] && j<=s2.length())
{
j++;
System.out.println(s2.length()+" "+j);
if(j>=s2.length())
{
System.out.println("first match of(The) :->"+i);
}
pf=pf+1;
}
}
}
for(int i=0;i<(s3.length()-s6.length()+1);i++)
{
int j=0;
if(pl<=1)
{
while (c5[i+j]==c3[j] && j<=s6.length())
{
j++;
System.out.println(s6.length()+" "+j);
if(j>=s6.length())
{
System.out.println((s3.length()-i-3));
pl=pl+1;
}
}
}
}
}
}

- 15
- 1
-
2put some explaination/comment in your code will make people easier to understand your code especially it's long code :) – himawan_r Jul 08 '15 at 08:19
//finding a particular word any where inthe string and printing its index and occurence
class IndOc
{
public static void main(String[] args)
{
String s="this is hyderabad city and this is";
System.out.println("the given string is ");
System.out.println("----------"+s);
char ch[]=s.toCharArray();
System.out.println(" ----word is found at ");
int j=0,noc=0;
for(int i=0;i<ch.length;i++)
{
j=i;
if(ch[i]=='i' && ch[j+1]=='s')
{
System.out.println(" index "+i);
noc++;
}
}
System.out.println("----- no of occurences are "+noc);
}
}

- 11
- 1
-
3While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Peter Brittain Sep 01 '15 at 07:50
String match = "hello";
String text = "0123456789hello0123456789hello";
int j = 0;
String indxOfmatch = "";
for (int i = -1; i < text.length()+1; i++) {
j = text.indexOf("hello", i);
if (i>=j && j > -1) {
indxOfmatch += text.indexOf("hello", i)+" ";
}
}
System.out.println(indxOfmatch);

- 11
- 1
If you're going to scan for 'n' matches of the search string, I'd recommend using regular expressions. They have a steep learning curve, but they'll save you hours when it comes to complex searches.

- 113
- 1
- 7
-
2Suggestion: Include an example of getting position from a regular expression. Just "try using regular expressions" is a rather basic comment and doesn't answer the OP's question. – Brad Koch Oct 15 '15 at 14:50
for multiple occurrence and the character found in string??yes or no
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SubStringtest {
public static void main(String[] args)throws Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the string");
String str=br.readLine();
System.out.println("enter the character which you want");
CharSequence ch=br.readLine();
boolean bool=str.contains(ch);
System.out.println("the character found is " +bool);
int position=str.indexOf(ch.toString());
while(position>=0){
System.out.println("the index no of character is " +position);
position=str.indexOf(ch.toString(),position+1);
}
}
}

- 4,347
- 8
- 29
- 44

- 1
- 2
public int NumberWordsInText(String FullText_, String WordToFind_, int[] positions_)
{
int iii1=0;
int iii2=0;
int iii3=0;
while((iii1=(FullText_.indexOf(WordToFind_,iii1)+1))>0){iii2=iii2+1;}
// iii2 is the number of the occurences
if(iii2>0) {
positions_ = new int[iii2];
while ((iii1 = (FullText_.indexOf(WordToFind_, iii1) + 1)) > 0) {
positions_[iii3] = iii1-1;
iii3 = iii3 + 1;
System.out.println("position=" + positions_[iii3 - 1]);
}
}
return iii2;
}

- 147
- 1
- 6
-
Hope It will solve issue but please add explanation of your code with it so user will get perfect understanding which he/she really wants. – Jaimil Patel May 29 '20 at 08:53
class Main{
public static int string(String str, String str1){
for (int i = 0; i <= str.length() - str1.length(); i++){
int j;
for (j = 0; j < str1.length(); j++) {
if (str1.charAt(j) != str.charAt(i + j)) {
break;
}
}
if (j == str1.length()) {
return i;
}}
return -1;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
String str=sc.nextLine();
System.out.println("Enter the Substring");
String str1=sc.nextLine();
System.out.println("The position of the Substring is "+string(str, str1));
}
}

- 1
-
1As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 21 '22 at 15:54