Question

[Running Java 1.7.0_51 on MacOSX]

Hello there,

I am currently writing a program, and have to write a method that will take a string parameter of a word, remove its punctuation, abbreviate the word itself, then once the word has been abbreviated, re-add the punctuation and return the word.
Note that the punctuation only includes: , ; . ! ?

The string parameter will be a single word, with punctuation only included at the end.

I already know how to do this with repeated if statements / else if, however I'd like to see an example of perhaps a better, more efficient way to do this if possible. I'm sure there's a better way, and that someone better experienced can give me an example. I'd be very grateful. I'm still learning but I'd like to explore efficient options!

Example input:
Thankyou!

Example output:
Ty!

All I need guidance with is the actual removing and re-adding punctuation. Leave the abbreviating part to me. So to just simplify it, assume that the input and output is unchangeable.

Was it helpful?

Solution

Considering

The punctuation mark is always at the end

You can get the punctuation mark from the inputWord as following:

String punctuation = inputWord.substring(inputWord.length() - 1);

and check it using regex if it is one of the punctuation mark you should have

if (punctuation.matches("[\\!\\,\\?\\;\\.]"))
    // your actions items here

this way you can avoid multiple if statements.


Alternatively

You can maintain a set of all the punctuation marks you need to check against:

Set<String> punctuationSet = new HashSet<String>(                                   
                        Arrays.asList(new String[]{"!", "?", ";", ",", "."}));

and later check if the punctuation in the inputWord is present in the punctuationSet using

if (punctuationSet.contains(punctuation))
    // your actions items here
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top