How to find all instances of sub-string within a String using indexOf() in Java

2 Answers

0 votes
package javaapplication1;

import java.io.IOException;

public class JavaApplication1 {

    public static void main(String[] args) throws IOException {

        try {

            String s = "abc abc abc bc";

            int pos = 0, count = 0;
            while ((pos = s.indexOf("bc", pos)) != -1) {
                System.out.println(pos);
                System.out.println(s.substring(pos));
                pos++;
                count++;
            }
            if (count > 0)
                System.out.println("found total of: " + count + " instances");
            else
                System.out.println("not found");

        } catch (Exception e) {
            System.out.print(e.toString());
        }
    }
}

/*
           
run:
     
1
bc abc abc bc
5
bc abc bc
9
bc bc
12
bc
found total of: 4 instances
  
 */

 



answered Nov 21, 2016 by avibootz
0 votes
package javaapplication1;

import java.io.IOException;

public class JavaApplication1 {

    public static void main(String[] args) throws IOException {

        try {

            String s = "abcabcabcbc";

            int pos = 0, count = 0;
            while ((pos = s.indexOf("bc", pos)) != -1) {
                System.out.println(pos);
                System.out.println(s.substring(pos));
                pos++;
                count++;
            }
            if (count > 0)
                System.out.println("found total of: " + count + " instances");
            else
                System.out.println("not found");

        } catch (Exception e) {
            System.out.print(e.toString());
        }
    }
}

/*
           
run:
     
1
bcabcabcbc
4
bcabcbc
7
bcbc
9
bc
found total of: 4 instances
  
 */

 



answered Nov 21, 2016 by avibootz

Related questions

...