Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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("?")) {
           sentenceCount++
 }

But instead I would want it to be something like:

if (word.endsWith(delimitersStringorArray.contains())  {
           sentenceCount++
     }

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

Thanks!

like image 514
Bryce Avatar asked Feb 08 '16 16:02

Bryce


2 Answers

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.

like image 143
Davide Lorenzo MARINO Avatar answered Nov 02 '22 06:11

Davide Lorenzo MARINO


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>();
delimiters.add('.'); 
delimiters.add('!');  
delimiters.add('?');  

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

  sentenceCount++;
}
like image 40
Arnaud Avatar answered Nov 02 '22 07:11

Arnaud