ChallengeChallenge

Note

To solve this task, you need to remember the methods charAt() and substring(). You can read more about them in Java Basics course.

Task

Your task is to write a method that returns the substring from the first occurrence of a character to its last occurrence. Then, you need to print the first and last letter of the obtained substring. Write two methods, where one will be used within the other.

java

Main.java

  1. 1. In the first method, use the indexOf() and lastIndexOf() methods to initialize integer variables;
    1. 2. Then, use the substring(first, last) method to initialize the result variable;
    2. 3. In the second method, use the charAt() method to initialize char variables. Remember that the first element is located at index 0, and the last element is located at index string.length() - 1;
    3. 4. Check the output result. The expected output should be e and m.

package com.example;

public class Main {
    static String makeSubstringFromToSymbol(String string, String symbols) {
        int firstIndex = string.indexOf(symbols);
        int lastIndex = string.lastIndexOf(symbols);
        String result = string.substring(firstIndex, lastIndex);
        return result;
    }

    static void findAndPrintFirstAndLastCharacters(String string) {
        char firstChar = string.charAt(0);
        char lastChar = string.charAt(string.length() - 1);
        System.out.println("First character = " + firstChar
                + " . Last character = " + lastChar);
    }
    
    // do not change code from below
    public static void main(String[] args) {
        String string = "This message need to be refactored within two methods!";
        String symbol = "e";
        findAndPrintFirstAndLastCharacters(makeSubstringFromToSymbol(string, symbol));
    }
    // do not change the code above
}
      

Everything was clear?

Section 3. Chapter 7