Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace first letter and last letter in array of strings

I am trying to replace in the array of strings in EVERY word, the first letter with A and the last letter with Z

My Array :

String[] replaceFirstLetter1 = new String[]{"Java Bople Orange New Dog Cat"};

This is what I am trying:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  public static String[] replaceFirstLetterWithZ(String[] replaceFirstLetter) {
        String[] tempTable = new String[replaceFirstLetter.length];
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < replaceFirstLetter.length; i++) {
            stringBuilder.append(replaceFirstLetter[i]);
            stringBuilder.replace(0, replaceFirstLetter.length, "A");
            stringBuilder.replace(replaceFirstLetter.length-1, replaceFirstLetter.length, "Z");
            tempTable[i] = stringBuilder.toString();
        }
        return tempTable;
    }

Anyhow my output is not what I am expecting
Output:

[Zava Bople Orange New Dog Cat]

Can any of you give a hand on what and where I should look for my mistake ?
Thanks

>Solution :

Regex is the goto tool here.

To replace the first and last words of every word in a string with A and Z:

str = str.replaceAll("\\w(\\w*)\\w", "A$1Z");

This works by matching words but capturing all characters of the word except the first and last characters, and replacing the match with A-group1-Z.

FYI words of only 1 letter are not matched.

To apply this to an array of String:

for (int i = 0; i < array.length; i++) {
    array[i] = array[i].replaceAll("\\w(\\w*)\\w", "A$1Z");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading