Find Strings Ending with a Specific Character

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

  1. Use a loop to iterate through each string in the array.
  2. For each string, compare the last character with the given target character.
  3. 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:

  1. The array words contains the strings, and targetChar is the character to check.
  2. The endsWith method of the String class is used to check if a word ends with the given character.
  3. The String.valueOf(targetChar) converts the character to a string for comparison.
  4. 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).

Java logical programs list


Java Basic Programs

Java String Programs

Java String Array Programs

Java Miscellaneous Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *