Header Ads Widget

Responsive Advertisement

Find the First & Last Occurrence in A String in JAVA

 



import java.util.*;

public class Recursion2 {
 public static int first = -1;
    public static int last = -1;

    // Find Occurrence ....

    public static void findOccurance(String str, int index, char element) {
        if (index == str.length()) {
            System.out.println("The First Occurance Found at Index : "+first);
            System.out.println("The Last Occurance Found at Index : "+last);
            return;
        }
        int current = str.charAt(index);
        if (current == element) {
            if (first == -1) {
                first = index;
            } else {
                last = index;
            }
        }
        findOccurance(str, index + 1, element);
    }
    public static void main(String[] args) {

        String str = "subhamoya";
 
        findOccurance(str, 0, 'a');
       

    }
}

Post a Comment

0 Comments