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
CodePudding user response:
Regex is the goto tool here.
To replace the first and last characters 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");
}
CodePudding user response:
Other than Regex that Bohemian mentioned (which is the norm for this kind of stuff), you can also do it manually by using substring
to remove the first and last characters:
public static void main(String[] args) {
String[] arr = replaceFirstLetterWithZ("Java Bople Orange New A Dog Cat".split(" "));
System.out.println(Arrays.toString(arr));
}
public static String[] replaceFirstLetterWithZ(String[] arr) {
for (int i = 0; i < arr.length; i ) {
if (arr[i].length() > 1) {
arr[i] = "A" arr[i].substring(1, arr[i].length() - 1) "Z";
}
}
return arr;
}
While using substring
, you will need to be careful to not get an StringIndexOutOfBoundsException
, so a check to make sure the size is greater than 1 is used, and if the String
does not meet the requirement, no replacing is done.
For example, the letter A
will not be replaced with anything because there are not two characters to replace.
Also notice the change to String[] replaceFirstLetter1 = new String[]{"Java Bople Orange New Dog Cat"};
in the main, you need to split
in order to break the String
into an array. The way you were doing it, the entire String
was in the same array element.
Output:
[AavZ, AoplZ, ArangZ, AeZ, A, AoZ, AaZ]