w3resource

Java: Return a string with the characters of the index position 0,1,2, 5,6,7, ... from a given string


97. Chars at Indices 0-2, 5-7, etc.

Write a Java program to return a string with characters at index positions 0,1,2,5,6,7, ... from a given string.

Visual Presentation:


Java String Exercises: Return a string with the characters of the index position 0,1,2, 5,6,7, ... from a given string


Sample Solution:

Java Code:

import java.util.*;

// Define a class named Main
public class Main {
  
  // Method to extract pairs of characters from the string
  public String pairsToReturn(String stng) {
    String fin_str = ""; // Initialize an empty string to store the modified string
    
    // Loop through the string with a step size of 5
    for (int i = 0; i < stng.length(); i += 5) {
      int end = i + 3; // Set the end index for extracting pairs
      
      // Check if the calculated end index is greater than the string's length
      if (end > stng.length()) {
        end = stng.length(); // If yes, update the end index to the string's length
      }
      
      // Extract a pair of characters from the string and append it to the final string
      fin_str = fin_str + stng.substring(i, end);
    }
    return fin_str; // Return the modified string
  }

  // Main method to execute the program
  public static void main(String[] args) {
    Main m = new Main(); // Create an instance of the Main class

    String str1 = "w3resource.com"; // Given string
    // Display the given string and the new string after extracting pairs
    System.out.println("The given string is: " + str1);
    System.out.println("The new string is: " + m.pairsToReturn(str1));
  }
}

Sample Output:

The given string is: w3resource.com
The new string is: w3rour.co

Flowchart:

Flowchart: Java String Exercises - Return a string with the characters of the index position 0,1,2,  5,6,7, ... from a given string



For more Practice: Solve these Related Problems:

  • Write a Java program to extract characters from a string at specific index intervals (e.g., indices 0-2, 5-7, etc.).
  • Write a Java program to form a new string by picking characters at positions that match a given pattern.
  • Write a Java program to generate a string using characters from fixed index blocks from the original string.
  • Write a Java program to create a new string by selecting characters from designated positions in the input string.

Go to:


PREV : Remove Char Except First and Last.
NEXT : Check Repeated Character at First Instance.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.