Java Substring Solution


Problem Overview

Original Problem: Java Substring | Hackerrank

Difficulty: Easy

Category: Strings

Description: We are given a string and two integers representing indices. Our task is to extract and print the portion of the string that starts at the first index and finishes just before the second index.

Understanding the Problem

This is a relatively simple problem where we just need to print a substring from the provided string using the provided indices.

Input:

We are provided with:

  • A string

  • Two integers representing the start and end indices

Output:

A single line containing the section of the string from the start index (inclusive) to the end index (exclusive).

Initial Reasoning

The original problem gives us template code to read in the three inputs. Since the substring method in Java follows the format string.substring(start, end), and it includes the character at the start index but excludes the character at the end index, the problem can be solved using a single line of code after reading inputs.

Pseudocode

// Main function:
Read the string input
Read the start and end indices
Extract the substring from start (inclusive) to end (exclusive)
Print the result

Solution Code

// Note this is one of many possible solutions
import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        // Create a scanner to read input
        Scanner scanner = new Scanner(System.in);
        
        // Read the input string
        String string = scanner.next();
        
        // Read the start and end indices
        int start = scanner.nextInt();
        int end = scanner.nextInt();
        
        // Extract the substring from start (inclusive) to end (exclusive)
        String result = string.substring(start, end);
        
        // Print the resulting substring
        System.out.println(result);
    }
}

Commenting on Alterations

While we have done our best to maintain similarity to the template code provided in the original problem, the following changes have been made to follow best practices:

  • Renamed variables:

    Using more descriptive names improves the clarity of the code and makes it easier for anyone reading the code to understand what each variable represents.