Q. How to extract characters from the string based on even indexes (starting from index 0) and manipulate the string to get the output “Fbur”.

Input: “February” Output: “Fbur”

Solution :-

You are given a string s = “February”. Your task is to create a new string containing only the characters at even indexes (0, 2, 4, 6) in the original string.

  • You should extract the characters at indexes 0, 2, 4, and 6 from the string “February”.

Concatenate these characters to form the output “Fbur”.

Requirements:

  1. Use indexing to retrieve characters at even positions.
  2. Optionally, use Java 8 Streams to filter characters based on even indexes.

public class Main {

public static void main(String[] args) {

        String s = “February”;

        // Extract characters at even indexes: 0, 2, 4, 6

        String result = s.substring(0, 1)   // “F” (index 0)

                      + s.substring(2, 3)   // “b” (index 2)

                      + s.substring(4, 5)   // “u” (index 4)

                      + s.substring(6, 7);  // “r” (index 6)

        // Print the result

        System.out.println(result);  // Output: “Fbur”

    }

}

Alternative Solution (Using Java 8 Streams):

Alternative Solution (Using Java 8 Streams):

For a more functional approach, you can use IntStream to filter characters at even indexes:

import java.util.stream.IntStream;

public class Main {

    public static void main(String[] args) {

        String s = “February”;

        // Use Java 8 Streams to filter even indexes and collect result

        String result = IntStream.range(0, s.length())

                                 .filter(i -> i % 2 == 0) // Select even indexes

                                 .mapToObj(s::charAt)

                                 .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)

                                 .toString();

        // Print the result

        System.out.println(result);  // Output: “Fbur”

    }

}

***************************************************************

Leave a Reply

Your email address will not be published. Required fields are marked *

*