Java: Read a string, if the first or last characters are same return the string without those characters otherwise return the string unchanged
Write a Java program to read a given string and return the string without the first or last characters if they are the same, otherwise return the string without the characters.
Visual Presentation:
Sample Solution:
Java Code:
import java.util.*;
// Define a class named Main
public class Main {
// Method to exclude 't' character from the string based on certain conditions
public String excludeT(String stng) {
// If the length of the input string is 0, return the input string
if (stng.length() == 0)
return stng;
// If the length of the input string is 1
if (stng.length() == 1) {
// If the string contains 't', return an empty string; otherwise, return the string itself
if (stng.charAt(0) == 't')
return "";
else
return stng;
}
// If the first character of the input string is 't', remove it from the string
if (stng.charAt(0) == 't')
stng = stng.substring(1, stng.length());
// If the last character of the input string is 't', remove it from the string
if (stng.charAt(stng.length() - 1) == 't')
stng = stng.substring(0, stng.length() - 1);
return stng; // 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 = "testcricket"; // Input string
// Display the given string and the new string using excludeT method
System.out.println("The given strings is: " + str1);
System.out.println("The new string is: " + m.excludeT(str1));
}
}
Sample Output:
The given strings is: testcricket The new string is: estcricke
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to remove the first and last characters of a string if they are identical.
- Write a Java program to conditionally trim a string’s boundaries based on whether the first and last characters match.
- Write a Java program to check if the first and last characters of a string are the same, then return the string without them.
- Write a Java program to remove matching boundary characters from a string and output the resulting substring.
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program to read a string and if a substring of length two appears at both its beginning and end,return a string without the substring at the beginning otherwise, return the original string unchanged.
Next: Write a Java program to read a string and return the string without the first two characters. Keep the first character if it is 'g' and keep the second character if it is 'h'.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.