javabukkitbungeecord

Loop through a string and prefix each character with a different value


I'm developing a command for my Minecraft server using Bungeecord and need a way to add a different colour code to the beginning of each character in a string. The hope being that I can turn any string they enter into being printed with a rainbow colour. I've been requested to use 8 different colour codes, and repeat the sequence for each 8 characters that pass.

I've registered the command and everything like that and it works, it's the string manipulation that I'm having trouble with. I know that to loop through a string I can use

String message;
for (int i = 0; i < message.toCharArray().size(); i++)
{
  char c = message.charAt(i);
  //Prefix code here
}

I've also defined the 8 colours I want to use

final String one = "4";
final String two = "6";
final String three = "e";
final String four = "a";
final String five = "b";
final String six = "9";
final String seven = "5";
final String eight = "d";

What I need is something that will accept a string such as

This text is now rainbow!

and will loop through every char and place "§one" - "§eight" in-front to colour each letter.

I've tried using String#replace(string, string) however this doesn't accept a char. I also tried using something along the lines of

String.replace("" + c, "§" + one + c);

However this didn't work either. Any help and/or pointers you could provide would be greatly appreciated :) Thank you

EDIT: Sample line of desired output

user does /rainbow This text is rainbow!

Output: §4T§6h§ei§as §bt§9e§5x§dt ...etc, but restart from §4


Solution

  • It will be easier if you store your colors in an array. Store the amount of colors in a variable so you don't keep doing colors.length in your loop.

    String [] colors = {"4", "6", "e", "a", "b", "9", "5", "d"};
    int numColors = colors.length;
    

    Create a StringBuilder:

    StringBuilder builder = new StringBuilder();
    

    Loop through the array of characters. Append the correct color to the character. i%numColors will allow the color array to go back to the beginning if your message string is greater than 8 characters since your array currently has 8 options.

    for(int i = 0; i < message.length(); i++){
        builder.append("§");
        builder.append(colors[i%numColors]);
        builder.append(message.charAt(i));
    }
    

    Then at the end of your method, just return the entire builder string.

    return builder.toString();
    

    If you want a space or a new line in between each character, just do builder.append "" or /n.