Java: Read a string and return the string without the first two characters
66. Remove First Two Except g or h
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:
For more Practice: Solve these Related Problems:
- Write a Java program to remove the first two characters of a string unless the first is 'g' or the second is 'h'.
- Write a Java program to conditionally retain the first two characters if they are 'g' or 'h', and remove them otherwise.
- Write a Java program to check the first two characters and remove them if they do not match the specified conditions.
- Write a Java program to process a string by preserving 'g' at the start and 'h' in the second position while truncating the rest.
Go to:
PREV : Remove Same First and Last Char.
NEXT : Remove Specified Start Characters.
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.