1.8.8 Creating some kind of String#replace

Discussion in 'Spigot Plugin Development' started by Wilsoon, Feb 20, 2020.

  1. So, I have my config.yml for my plugin, and I want anything from a stringlist of commands to change {target} to target.getName() and {challenger} to challenger.getName(), however I've tried
    Code (Java):

    for(String command : SpleefGame.getInstance().getConfig().getStringList("commands")) {
                    final ConsoleCommandSender console = Bukkit.getServer().getConsoleSender();
                    command.replace("{target}", player.getName());
                    command.replace("{challenger}", challenger.getName());
                    Bukkit.dispatchCommand(console, command);
                }
     
    and it doesn't seem to work, what's the right way to do it?
     
  2. String is immutable, so the replace method returns a new string and doesn't modify the original one. You need to use that new string to continue with.
     
    • Agree Agree x 1
  3. Try this:
    Code (Java):
    for (String command : SpleefGame.getInstance().getConfig().getStringList("commands")) {
        final ConsoleCommandSender console = Bukkit.getConsoleSender();
        Bukkit.dispatchCommand(console, command.replace("{target}", player.getName()).replace("{challenger}", challenger.getName()));
    }
     
    • Like Like x 1
  4. On a related note: String#replace uses a regular expression for its first argument (see the JavaDoc for Pattern). Some characters would need to be escaped, although this does not apply in your case. Just keep it in mind for the future. ;)
    Edit: Nevermind, thought of String#replaceAll.
     
    #4 Starjon, Feb 20, 2020
    Last edited: Feb 21, 2020
  5. Oh, thank you!
    Hmm, I don't seem to understand why the #replace is at Bukkit#dispatchCommand instead of being at a separate area.
     
  6. SteelPhoenix

    Moderator

    No it does not. String#replaceAll(...) Uses regex.
     
    • Like Like x 2
    • Agree Agree x 1
  7. In the example that doesn't really matter. You can first store it in a variable and then reference that variable inside the Bukkit.dispatchCommand, or you can put it directly in that method. Depending on what you prefer you can do either.