Wednesday 29 April 2020

Check whether given character present in string or not

Using ‘indexOf’ method, we can check whether given character is present in string or not. ‘indexOf()’ method return -1, if given character is not present in the string, else it return the index of the first occurrence of the character in the string.

Example
private static boolean isCharExist(String str, char ch) {
         if (str == null) {
                  throw new IllegalArgumentException("String can't be null");
         }

         return str.indexOf(ch) != -1;
}

Find the following working application.

App.java
package com.sample.app;

public class App {

 private static boolean isCharExist(String str, char ch) {
  if (str == null) {
   throw new IllegalArgumentException("String can't be null");
  }

  return str.indexOf(ch) != -1;
 }

 public static void main(String args[]) {
  String str = "Hello World";

  char ch = 'H';
  System.out.println("is " + ch + " exists in " + str + " : " + isCharExist(str, ch));

  ch = 'o';
  System.out.println("is " + ch + " exists in " + str + " : " + isCharExist(str, ch));

  ch = 'a';
  System.out.println("is " + ch + " exists in " + str + " : " + isCharExist(str, ch));
 }

}

Output
is H exists in Hello World : true
is o exists in Hello World : true
is a exists in Hello World : false


You may like

No comments:

Post a Comment