In this article, we will learn how to write a Java program to identify strings in an array that end with a given character. This problem is useful for practicing string manipulation and array traversal in Java.
Problem Description:
We are given an array of strings and a specific character. The task is to identify and display all strings in the array that end with the given character.
Approach to Solve the Problem
- Use a loop to iterate through each string in the array.
- For each string, compare the last character with the given target character.
- If a match is found, print the string.
Java program to find strings ending with a specific character
Here is the Java program to solve the problem:
package com.javacodepoint.stringarray;
public class StringEndsWith {
public static void main(String[] args) {
// Input array of strings
String[] words = { "apple", "banana", "cherry", "date" };
char targetChar = 'e';
// Loop through each word in the array
for (String word : words) {
if (word.endsWith(String.valueOf(targetChar))) {
System.out.println("The word \"" + word + "\" ends with '" + targetChar + "'.");
}
}
}
}
OUTPUT:
The word “apple” ends with ‘e’.
The word “date” ends with ‘e’.
Code Explanation:
- The array
words
contains the strings, andtargetChar
is the character to check. - The
endsWith
method of theString
class is used to check if a word ends with the given character. - The
String.valueOf(targetChar)
converts the character to a string for comparison. - The program iterates through each word and prints it if it matches the condition.
Conclusion
This program demonstrates how to identify strings that end with a specific character in an array. It is an excellent example of applying string methods in Java. Understanding this concept will help in text processing and search-related problems.
You can learn the Top 20 string array programs for interview preparation (Click here).