Java: Read a string and return true if it ends with a specified string of length 2
58. Ends With Specific Two Characters
Write a Java program to read a string and return true if it ends with a specified string of length 2.
Visual Presentation:
Sample Solution:
Java Code:
import java.util.*;
// Define a class named Main
public class Main {
// Method to check if the string ends with 'ng'
public boolean endsNg(String str) {
int len = str.length(); // Calculate the length of the input string
String ng = "ng"; // Define the string 'ng'
// If the length of the input string is less than 2 characters, return false
if (len < 2)
return false;
// If the last two characters of the input string match 'ng', return true
else if (ng.equals(str.substring(len - 2, len)))
return true;
// Otherwise, return false
else
return false;
}
// Main method to execute the program
public static void main(String[] args) {
Main m = new Main(); // Create an instance of the Main class
// Define a string to check if it ends with 'ng'
String str1 = "string";
// Display the given string and whether it contains 'ng' at the end using the endsNg method
System.out.println("The given string is: " + str1);
System.out.println("Does the string contain 'ng' at the end? " + m.endsNg(str1));
}
}
Sample Output:
The given strings is: string The string containing ng at last: true The given strings is: strign The string containing ng at last: false
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to check if a string concludes with a specified two-character substring and output a boolean value.
- Write a Java program to determine if the last two characters of a string match a given pair, ignoring case.
- Write a Java program to verify if a string ends with any of several given two-character combinations.
- Write a Java program to check a string's ending for a two-character pattern and handle strings shorter than two characters gracefully.
Go to:
PREV : Swap Last Two Characters.
NEXT : Begins With Color String.
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.