Frequently Asked Java Program 27: Java Program to Find Occurrence of Any Char in a Given String Without Iterating

Problem Statement:

Find occurrence of given char  (Ignore case)  in given string without iterating through string.

Input – Make Selenium Easy

Char – ‘M’

Output- Occurrence of M is 2.

Problem Solution:

We need to solve this problem without iterating through string in search of character. Its simple.

Logic step by step:

  1. FInd the initial length of given string.
  2. Replace desired char by empty character.
  3. Find the length of string after replacement.
  4. FInd the difference between initial and current length.
  5. The difference is occurrence of asked char in string.

 

Java Programs:

Output:

Please enter the string :
Make Selenium Easy
Please enter the char to find occurrence in : Make Selenium Easy
m
You entered: Make Selenium Easy
Char to be found: m
Count of m is :2
=================================================================
Please enter the string :
Autoation Tester
Please enter the char to find occurrence in : Autoation Tester
T
You entered: Autoation Tester
Char to be found: T
Count of T is :4
=================================================================

#HappyCoding

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

1 thought on “Frequently Asked Java Program 27: Java Program to Find Occurrence of Any Char in a Given String Without Iterating

  1. There is a another easy way for the same question:

    Please give your suggesion on this:

    package basicJava;

    import java.util.Scanner;

    public class OccuOfCharInString {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println(“Enter the String :”);
    Scanner scan = new Scanner(System.in);
    String str=scan.nextLine();
    System.out.println(“Enter the chat need to find the occurance:”);
    char ch=scan.nextLine().charAt(0);
    int count=0;
    for(int i=0;i<str.length();i++) {
    if(ch==str.charAt(i)) {
    count++;
    }
    }
    System.out.println("The total number of occurance of given char is "+count);
    }

    }

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.
%d bloggers like this: