Maison  >  Article  >  Java  >  Pourquoi ma méthode de remplacement de chaîne Java ne met-elle pas à jour la chaîne ?

Pourquoi ma méthode de remplacement de chaîne Java ne met-elle pas à jour la chaîne ?

Linda Hamilton
Linda Hamiltonoriginal
2024-11-14 11:48:02457parcourir

Why Isn't My Java String Replace Method Updating the String?

Java String Replace Method Behaving Unexpectedly

In Java, the String replace method is a commonly used function for replacing occurrences of a substring with a new string. However, sometimes users encounter situations where the replace method appears to be malfunctioning.

Consider the following code snippet:

String delimiter = "\\*\\*";
String html = "<html><head></head><body>**USERNAME** AND **PASSWORD**</body></html>";
Map<String, String> mp = new HashMap<>();
mp.put("USERNAME", "User A");
mp.put("PASSWORD", "B");
for (Entry<String, String> entry : mp.entrySet()) {
  html.replace(delimiter + entry.getKey()+ delimiter, entry.getValue());
}

In this code, the goal is to replace the placeholders for USERNAME and PASSWORD in the HTML string with the corresponding values from the map provided. However, upon execution, the original HTML string html remains untouched, leading to困惑ion.

Understanding the Issue

To understand the issue, we need to remember that Strings in Java are immutable, meaning they cannot be modified in place. The replace method on strings returns a new String object containing the modified values. In our code, we are not capturing the result of the replace method and assigning it back to the original html variable. As a result, the changes are not being applied to the original string.

Solution

To resolve this issue, we need to capture the result of the replace method and assign it back to the html variable:

html = html.replace(delimiter + entry.getKey()+ delimiter, entry.getValue());

With this modification, the code will now correctly update the html string with the desired replacement values.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn