Java: Return a string with the characters of the index position 0,1,2, 5,6,7, ... from a given string
Java String: Exercise-97 with Solution
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:
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:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program to create a new string after removing a specified character from a given string except the first and last position.
Next: Write a Java program to check whether the first instance of a given character is immediately followed by the same character in a given string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/string/java-string-exercise-97.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics