Java 11 and 12 added several new String
methods, including indent(int n)
, stripLeading()
and stripTrailing()
, Stream<T> lines()
, isBlank()
, and transform()
.
You want to break a string apart, either by indexing positions or by using fixed token characters (e.g., break on spaces to get words).
For substrings, use the String object’s substring()
method. For tokenizing, construct a StringTokenizer
around your string and call its methods hasMoreTokens()
and nextToken()
.
Or, use regular expressions.
You need to put some String pieces (back) together.
Use string concatenation: the +
operator. The compiler implicitly constructs a StringBuilder
for you and uses its append()
methods (unless all the string parts are known at compile time).
Better yet, construct and use a StringBuilder
yourself.
You want to process the contents of a string, one character at a time.
Use a for loop and the String’s charAt()
or codePointAt()
method. Or use a “for each” loop and the String’s toCharArray
method.
You want to convert between Unicode characters and Strings.
Use Java char
or String
data types to deal with characters; these intrinsically support Unicode. Print characters as integers to display their raw value if needed.