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

I am new to Java, and I'm currently writing a program that uses arguments using the entered arguments to delimit the text file containing sentences, and then determines the number of sentences in this text file based on the provided delimiters.

When starting my Main.java, I want the user to be able to do the following (where -d is the flag for the separator, and the following characters are the separators):

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

Or any other combination. My questions:

  • Best way to store delimiters as strings or arrays?
  • How can I say that my program uses transmittable delimiters? Currently, my program does the following:

Checks if a word ends with any of the specified delimiters. For instance:

if (word.endsWith(".") || word.endsWith("!") || word.endsWith("?")) { sentenceCount++ } 

But instead, I would like it to be something like:

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

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

Thanks!

+5
source share
2 answers

It is probably best to have a String array as the delimiter. This is because the endsWith method uses String as a parameter.

The problem is that the actual version of endWith in the java.lang.String class does not accept an array of possible delimiters, but you can create your own code to do the same thing as 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 the following code

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

Please note that this is more general code than what you requested, because you can check if the transmitted string ends with separators of more than one character.

+4
source

If your delimiter is only one character long, you can save the delimiters in a List , and then check to see 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++; } 
+3
source

Source: https://habr.com/ru/post/1242556/


All Articles