Sub topic 7
Creating Transformed Strings
A string transformation changes text into a form you need. For example, you might remove spaces from the ends of a label, change letters to lowercase, or replace dashes with underscores.
In Java, a String is immutable. This means its text cannot be changed after it is created. A transformation method returns a string containing the result; it does not change the original string.
This matters because calling a method is not enough. You must use or save the result if you want to keep it.
A worked example
Suppose a program receives the label Java-STRINGS . You want to turn it into java_strings for use as a simple key.
A method is an action you can call on a value. A return value is the result a method gives back. The program below saves each return value in a variable, which is a named place to store a value.
Save this program as TransformText.java. It uses Java 11 or later.
import java.util.Locale;
class TransformText {
public static void main(String[] args) {
String raw = " Java-STRINGS ";
String trimmed = raw.strip();
String lower = trimmed.toLowerCase(Locale.ROOT);
String key = lower.replace("-", "_");
System.out.println("raw = [" + raw + "]");
System.out.println("trimmed = [" + trimmed + "]");
System.out.println("lower = [" + lower + "]");
System.out.println("key = [" + key + "]");
}
}Run it with:
javac TransformText.java
java TransformTextThe output is:
raw = [ Java-STRINGS ]
trimmed = [Java-STRINGS]
lower = [java-strings]
key = [java_strings]The square brackets make the spaces at the ends easier to see. Notice that raw still has its original text. Each step uses the result of the previous step.
A transformation may return the original string when no change is needed. Do not depend on getting a different object. The important point is that the original text stays unchanged.
Save the result
This call returns an uppercase string:
message.toUpperCase(Locale.ROOT);
But if the program ignores the return value, message still holds its original text. To keep the result, assign it:
message = message.toUpperCase(Locale.ROOT);
The variable now holds the uppercase result. The string that message held before was not changed.
Remove space from the ends
The strip method removes whitespace from the beginning and end of a string. Whitespace is space-like text, such as spaces, tabs, and line breaks. Whitespace inside the string stays in place.
| Original text | After `strip()` |
|---|---|
| ` red apple ` | `red apple` |
| ` red apple ` | `red apple` |
| ` ` | An empty string |
An empty string contains no text. A string made only of whitespace becomes empty after strip().
Java also has methods for removing whitespace from just one end:
stripLeading()removes it from the beginning.stripTrailing()removes it from the end.
These methods can help when space at one end is meaningful. For example, if a user typed extra spaces after a label, stripTrailing() leaves any spaces at the beginning alone.
`strip` and `trim`
You may see the older trim() method in Java programs. It removes characters with values up to U+0020 from the ends. This includes ordinary spaces, but it uses a narrower rule than strip() for many kinds of whitespace.
The strip() method uses Java's Character.isWhitespace rule. Even that rule does not cover every character that looks like a space. For example, a non-breaking space is not removed by strip(). If your input can contain unusual spaces, decide which ones your program should remove and test them.
Change letter case
Use toLowerCase to get lowercase text and toUpperCase to get uppercase text. In the worked example, toLowerCase(Locale.ROOT) turns Java-STRINGS into java-strings.
A locale is a set of language and region rules. Letter case can depend on those rules. Locale.ROOT uses language-neutral rules, which are often useful for internal keys such as java_strings.
For text shown to people in a particular language, language-neutral rules may not be the right choice. Also, changing case is not the same as checking every possible form of equivalent text. Some letters can even change into more than one letter when their case changes.
Do not change the case of passwords or other exact values unless the rules of your program specifically require it. A transformation can remove information that the user meant to keep.
Replace text
The replace method returns text with matching parts replaced. An argument is a value passed to a method. In replace("-", "_"), the first argument is the text to find and the second is the text to put in its place.
Replacement is case-sensitive: lowercase cat does not match uppercase CAT. It replaces every matching part, not just the first one.
Save and run this example as ReplaceText.java:
class ReplaceText {
public static void main(String[] args) {
String text = "cat.cat cat";
System.out.println(text.replace("cat", "dog"));
System.out.println(text.replace(".", "-"));
System.out.println(text.replace("CAT", "dog"));
System.out.println(text.replace("cat", ""));
System.out.println(text);
}
}javac ReplaceText.java
java ReplaceTextThe output is:
dog.dog dog
cat-cat cat
cat.cat cat
.
cat.cat catThe fourth result contains a period followed by a space. Replacing cat with an empty string removes each match. The last line shows that the original text did not change.
The period in replace(".", "-") means a literal period. A literal is the exact text written between the quotation marks. Java also has replaceAll, which treats its first argument as a pattern rather than plain text. Use replace when you want to replace exact text.
When matches could overlap, replace uses matches from left to right without overlapping them. For example, "aaaa".replace("aa", "b") produces bb.
Chain transformations
A chain calls the next method on the result of the previous method. The steps from the first example can be written as one expression:
raw.strip().toLowerCase(Locale.ROOT).replace("-", "_")
Java first strips the ends, then changes the case, then replaces dashes. You can save the final result like this:
String key = raw.strip().toLowerCase(Locale.ROOT).replace("-", "_");
Chaining is useful when the steps are short and clear. Separate variables, as in the worked example, can make each result easier to inspect when something goes wrong.
The order can matter. If you replace spaces with dashes before calling strip(), there may be no spaces left at the ends for strip() to remove. Choose the order based on the result you need.
Check your result
Before you use a transformed value, ask:
- Did I save or use the returned string?
- Should I remove whitespace from both ends, one end, or neither?
- Should replacement be case-sensitive?
- Could the transformation remove information that needs to stay?
- Does the order of the steps produce the intended text?
Try the transformation on an empty string and on text that needs no changes. If the program receives user input, also try input with extra spaces and unexpected letter case.
Exercises
Exercise
A variable named word holds " JAVA ". What does word.strip().toLowerCase(Locale.ROOT) return, and what does word still hold?
Show answer
It returns "java". The variable word still holds " JAVA " unless you assign a new value to it.
Exercise
What does "red.red".replace(".", "-") return? Does it change the original string?
Show answer
It returns "red-red". It does not change the original string.
Exercise
Why might stripping spaces before replacing spaces with dashes give a different result from replacing first?
Show answer
Replacing first turns the end spaces into dashes, so strip() no longer removes them.