ChallengeChallenge

Task

Write a method that finds the indices of the first and last occurrence of a character in a string and returns their sum. Keep in mind that some letters may be in uppercase, so convert the string to lowercase beforehand.

java

Main.java

  1. 1. Create a variable to store the index of the first occurrence of the character;
    1. 2. Initialize it using the indexOf(symbols) method, making sure to convert the string to lowercase;
    2. 3. Create another variable to store the index of the last occurrence of the character;
    3. 4. Initialize this variable using the lastIndexOf(symbols) method, also converting the string to lowercase;
    4. 5. Return the result using the syntax return firstVariable + secondVariable;.

package com.example;

public class Main {
    static int findSumOfFirstAndLastIndex(String string, String symbols) {
         return string.toLowerCase().indexOf(symbols)
                + string.toLowerCase().lastIndexOf(symbols);
    }

    // do not change code from below
    public static void main(String[] args) {
        String first = "Hey, I love Java, and want to learn it";
        String second = "I am learning Java at c<>definity";
        int firstSum = findSumOfFirstAndLastIndex(first, "i");
        int secondSum = findSumOfFirstAndLastIndex(second, "ni");
        System.out.println("Result in the first string = " + firstSum);
        System.out.println("Result in the second string = " + secondSum);
    }
    // do not change the code above
}
      

Everything was clear?

Section 3. Chapter 5