mardi 30 juin 2020

Reverse words without changing capitals or punctuation

Create a program with the lowest amount of characters to reverse each word in a string while keeping the order of the words, as well as punctuation and capital letters, in their initial place.

By "Order of the words," I mean that each word is split by a empty space (" "), so contractions and such will be treated as one word. The apostrophe in contractions should stay in the same place. ("Don't" => "Tno'd").

(Punctuation means any characters that are not a-z, A-Z or whitespace*).

Numbers were removed from this list due to the fact that you cannot have capital numbers. Numbers are now treated as punctuation.

For example, for the input:

Hello, I am a fish.

it should output:

Olleh, I ma a hsif.

Notice that O, which is the first letter in the first word, is now capital, since H was capital before in the same location.

The comma and the period are also in the same place.

More examples:

This; Is Some Text!

would output

Siht; Si Emos Txet!

public static String reverseWord(String input) {

        String words[]=input.split(" ");
         StringBuilder result=new StringBuilder();
       
          for (String string : words) {
              String revStr = new StringBuilder(string).reverse().toString();
              result.append(revStr).append(" ");
          }
        return result.toString().trim();
        
    } 



Aucun commentaire:

Enregistrer un commentaire