How to search for a character in a String using charAt() in Java

1 Answer

0 votes
package javaapplication1;

import java.io.IOException;

public class JavaApplication1 {

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

        try {

            String s = "Java Code";
            char ch = 'a';
            int i;
            
            for (i = 0; i < s.length(); i++) 
                if (s.charAt(i) == ch) 
                    break;
            
            if (i < s.length())
                System.out.println("found on index: " + i);
            else
                System.out.println("not found");

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

/*
           
run:
     
found on index: 1
  
 */

 



answered Nov 21, 2016 by avibootz
...