Java: Read a string and return the string without the first two characters
Java String: Exercise-66 with Solution
Write a Java program to read a string and return it without the first two characters. Keep the first character if it is 'g' and keep the second character if it is 'h'.
Visual Presentation:
Sample Solution:
Java Code:
import java.util.*;
// Define a class named Main
public class Main {
// Method to exclude first 'g' and second 'h' characters from the input string
public String exceptFirstTwo(String stng) {
// Get the length of the input string
int len = stng.length();
String temp = ""; // Create an empty string
// Iterate through each character in the input string
for (int i = 0; i < len; i++) {
// If the current index is 0 and the character is 'g', append 'g' to the temporary string
if (i == 0 && stng.charAt(i) == 'g')
temp += 'g';
// If the current index is 1 and the character is 'h', append 'h' to the temporary string
else if (i == 1 && stng.charAt(i) == 'h')
temp += 'h';
// If the current index is greater than 1, append the character to the temporary string
else if (i > 1)
temp += stng.charAt(i);
}
return temp; // 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 = "ghost"; // Input string
// Display the given string and the new string using exceptFirstTwo method
System.out.println("The given strings is: " + str1);
System.out.println("The new string is: " + m.exceptFirstTwo(str1));
}
}
Sample Output:
The given strings is: goat The new string is: gat he given strings is: photo The new string is: hoto The given strings is: ghost The new string is: ghost
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program to read a given string and if the first or last characters are same return the string without those characters otherwise return the string unchanged.
Next: Write a Java program to read a string and if one or both of the first two characters is equal to specified character return without those characters otherwise return the string unchanged.
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-66.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics