Java String.replace
String.replace substitutes every occurrence of a literal character or sequence. It returns a new string that you can put on the label.
A simple example
String.replace
- Start with "a-b"
- Do this Replace the hyphen with a space
- Result "a b"
class Main {
public static void main(String[] args) throws Exception {
System.out.println("a-b".replace('-', ' '));
}
}
a b
Syntax
label.replace("_", " ")
JDK 21 method signatures (2)
public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaTurn shelf codes into readable labels
A printed code uses separators or spacing that are awkward for a reader. Convert the display copy to the desired format and preserve the original value needed by the source system.
public class Main {
public static void main(String[] args) throws Exception {
String code = "DRIED_RED_BEANS";
System.out.println(code.replace("_", " "));
System.out.println(code);
}
}
DRIED RED BEANS DRIED_RED_BEANS
Both underscores become spaces in the printed label. Printing code afterward shows the original value.
Standardize a printed phone extension
A phone list prints internal extensions with punctuation inherited from an older directory. Replace the separator intended by the printer without changing the digits staff need to dial.
class Main {
public static void main(String[] args) throws Exception {
String extension = "01.02.03";
System.out.println(extension.replace(".", "-"));
}
}
01-02-03
Every literal dot becomes a hyphen.
Rename an item throughout a menu
A café changes the name of an item throughout its menu. Replace every intended occurrence in the display text and check that the new name appears wherever a customer would see it.
class Main {
public static void main(String[] args) throws Exception {
String menu = "iced tea + tea cake";
System.out.println(menu.replace("tea", "mint"));
}
}
iced mint + mint cake
Both occurrences change, including the one inside the second item name.
What to watch for
Use the returned string. The original text keeps its underscores.