Java Development: How to Find the Initial and Final Letter Occurrences?

2 0
Read Time:1 Minute, 0 Second

Write a program to find the first and the last occurrence of the letter ‘o’ and character ‘,’ in “Hello, World”.

public class OccurrenceFinder {
    public static void main(String[] args) {
        String input = "Hello, World";
        char targetChar1 = 'o';
        char targetChar2 = ',';

        int firstOccurrence1 = -1;
        int lastOccurrence1 = -1;
        int firstOccurrence2 = -1;
        int lastOccurrence2 = -1;

        for (int i = 0; i < input.length(); i++) {
            char currentChar = input.charAt(i);
            
            if (currentChar == targetChar1) {
                if (firstOccurrence1 == -1) {
                    firstOccurrence1 = i;
                }
                lastOccurrence1 = i;
            }
            
            if (currentChar == targetChar2) {
                if (firstOccurrence2 == -1) {
                    firstOccurrence2 = i;
                }
                lastOccurrence2 = i;
            }
        }

        System.out.println("First occurrence of 'o': " + firstOccurrence1);
        System.out.println("Last occurrence of 'o': " + lastOccurrence1);
        System.out.println("First occurrence of ',': " + firstOccurrence2);
        System.out.println("Last occurrence of ',': " + lastOccurrence2);
    }
}

When you run this program, it will output:

First occurrence of 'o': 4
Last occurrence of 'o': 7
First occurrence of ',': 5
Last occurrence of ',': 5

This means that the first occurrence of the letter ‘o’ is at index 4, the last occurrence of ‘o’ is at index 7, the first occurrence of ‘,’ is at index 5, and the last occurrence of ‘,’ is also at index 5 in the string “Hello, World”.

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Comment

Verified by MonsterInsights