Title here
Summary here
The standard library’s String
class provides many useful string-related methods. Here are some examples to give you a sense of the available functionality.
import java.util.Arrays;
public class StringFunctions {
// We create a shorthand for System.out.println as we'll use it a lot below.
private static void p(Object... args) {
System.out.println(Arrays.toString(args));
}
public static void main(String[] args) {
// Here's a sample of the methods available in String.
// Since these are methods on the String object itself,
// we call them directly on the string in question.
// You can find more methods in the String class documentation.
p("Contains: ", "test".contains("es"));
p("Count: ", "test".chars().filter(ch -> ch == 't').count());
p("HasPrefix: ", "test".startsWith("te"));
p("HasSuffix: ", "test".endsWith("st"));
p("Index: ", "test".indexOf("e"));
p("Join: ", String.join("-", "a", "b"));
p("Repeat: ", "a".repeat(5));
p("Replace: ", "foo".replaceAll("o", "0"));
p("Replace: ", "foo".replaceFirst("o", "0"));
p("Split: ", Arrays.toString("a-b-c-d-e".split("-")));
p("ToLower: ", "TEST".toLowerCase());
p("ToUpper: ", "test".toUpperCase());
}
}
When you run this program, you’ll get:
$ javac StringFunctions.java
$ java StringFunctions
[Contains: , true]
[Count: , 2]
[HasPrefix: , true]
[HasSuffix: , true]
[Index: , 1]
[Join: , a-b]
[Repeat: , aaaaa]
[Replace: , f00]
[Replace: , f0o]
[Split: , [a, b, c, d, e]]
[ToLower: , test]
[ToUpper: , TEST]
In this Java version, we’ve used methods directly on the String
objects where possible. For operations not directly available as methods, we’ve used alternative approaches:
Count
, we used the chars()
stream and counted the occurrences.Join
is a static method in the String
class in Java.Split
returns an array, so we used Arrays.toString()
to print it.The rest of the operations have direct equivalents in Java’s String
class.