Remove the last letter of every String in Array [JAVA]

108 views Asked by At

As the title says.

In want to remove the last letter of every word in an array and put it to the beginning of every word.

Here's an example (Input):

Hello I am a player

And here's the output:

oHell I ma a rplaye

I tried:

StringBuffer lastChar = new StringBuffer(output);
lastChar.deleteCharAt(lastChar.length()-1);
System.out.println(lastChar);

But it will just remove the last char of the String and won't put it to the beginning. AND does it only for a whole sentence and not for every word individually.

Love your help here!

4

There are 4 answers

6
Orcazephyr On

First, we must parse the string into its words. We can do this with

String[] words = input.split(" ");

After we have an array of words, we just have to loop through it and modify each element.

for (int i = 0; i < words.length; i++) {
    String word = words[i];
    String lastChar = word.substring(word.length() - 1);
    words[i] = lastChar + word.substring(0, word.length() - 1);
}

Finally, we have to recombine the array into a single string.

String result = String.join(" ", words);
1
Bohemian On

Here's a one liner:

str = Arrays.stream(str.split(" "))
    .map(s -> s.replaceAll("(.*)(.)", "$2$1"))
    .collect(Collectors.joining(" "));

The main operation is replaceAll("(.*)(.)", "$2$1") which captures all but the last characters as group 1, and the last char as group 2, and replaces the entire string with group 2 then group 1, effectively "moving" the last char to the front.

0
AudioBubble On

Try this.

Pattern PAT = Pattern.compile("(\\w*)(\\w)");
String input = "Hello I am a player";
String output = PAT.matcher(input).replaceAll(m -> m.group(2) + m.group(1));
System.out.println(output);

output:

oHell I ma a rplaye
0
shmosel On

You can split it into words and then rotate the characters in each word using Collections.rotate():

String rotate(String word) {
    String[] chars = word.split("");
    Collections.rotate(Arrays.asList(chars), 1);
    return String.join("", chars);
}

Ideone Demo