Home Ask Login Register

Developers Planet

Your answer is one click away!

Bryce February 2016

Java - If word ends with user-entered delimiters, then do x

I am new to Java and am currently writing a program that takes use-entered arguments for delimiters of a text file containing sentences, and then determines the number of sentences within that text file based on the provided delimiters.

When running my Main.java I want the user to be able to do the following (where -d is the flag for delimiter and the characters following are the delimiters):

java Main -d !?. or java Main -d .?

Or any other combination. My questions are:

  1. Is the best way to store the delimiters as a string or array?
  2. How do I cleanly tell my program to use the delimiters being passed? Currently my program does the following:

Checks to see if a word ends with any of the delimiters specified. Like:

 if (word.endsWith(".")  || word.endsWith("!")  || word.endsWith("?")) {

But instead I would want it to be something like:

if (word.endsWith(delimitersStringorArray.contains())  {

I hope this makes sense and I can provide any further clarification if necessary. I tried searching but did not find my specific question.



Berger February 2016

If your delimiter is only one character long, you could store the delimiters in a List, then check if the last character of the String is in this list :

List<Character> delimiters = new ArrayList<Character>();

if(delimiters.contains(word.charAt(word.length() - 1))){


Davide Lorenzo MARINO February 2016

Probably the best is to have as delimiter a String array. That because the method endsWith use a String as a parameter.

The problem is that the actual version of endsWith in the class java.lang.String doesn't accept an array of possible delimiters, but it is possible to create a custom code to do the same like the following:

public class StringUtility {
    public static boolean endsWith(String str, String[] delimiters) {
        for (String delimiter : delimiters) {
            if (str.endsWith(delimiter)) {
                return true;
        return false;

And to call it use a code like the following

String[] delimiters = { ".", "!", "?" };
if (StringUtility.endsWith("yourWord", delimiters)) {
    // Do something

Note that this is a more general code then what you requested because you can check if the passed string ends with delimiters of more than one characters.

Post Status

Asked in February 2016
Viewed 3,987 times
Voted 9
Answered 2 times


Leave an answer

Quote of the day: live life