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:
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");
}