Library contents

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

  1. Start with "a-b"
  2. Do this Replace the hyphen with a space
  3. Result "a b"
The surrounding letters keep their positions relative to one another.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("a-b".replace('-', ' '));
    }
}
Output
a b

Syntax

Java 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.java

Turn 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.

From the programString code = "DRIED_RED_BEANS"
First output lineDRIED RED BEANS
Main.java
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);
    }
}
Output
DRIED RED BEANS
DRIED_RED_BEANS

Both underscores become spaces in the printed label. Printing code afterward shows the original value.

Advertisements

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.

From the programString extension = "01.02.03"
Result01-02-03
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String extension = "01.02.03";
        System.out.println(extension.replace(".", "-"));
    }
}
Output
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.

From the programString menu = "iced tea + tea cake"
Resulticed mint + mint cake
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String menu = "iced tea + tea cake";
        System.out.println(menu.replace("tea", "mint"));
    }
}
Output
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.

Documentation for String.replace