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 {
public static void main(String[] args) {
// We use System.out.println directly as it's already short in Java
// Here's a sample of the methods available in String class.
// Since these are methods on the string object itself,
// we call them directly on the string. You can find more
// methods in the String class documentation.
System.out.println("Contains: " + "test".contains("es"));
System.out.println("Count: " + countOccurrences("test", 't'));
System.out.println("HasPrefix: " + "test".startsWith("te"));
System.out.println("HasSuffix: " + "test".endsWith("st"));
System.out.println("Index: " + "test".indexOf("e"));
System.out.println("Join: " + String.join("-", "a", "b"));
System.out.println("Repeat: " + "a".repeat(5));
System.out.println("Replace: " + "foo".replace("o", "0"));
System.out.println("Replace: " + "foo".replaceFirst("o", "0"));
System.out.println("Split: " + Arrays.toString("a-b-c-d-e".split("-")));
System.out.println("ToLower: " + "TEST".toLowerCase());
System.out.println("ToUpper: " + "test".toUpperCase());
}
// Java doesn't have a built-in count method, so we implement it
private static int countOccurrences(String str, char ch) {
return (int) str.chars().filter(c -> c == ch).count();
}
}
When you run this program, you’ll see:
$ 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
This example demonstrates various string operations in Java. Note that unlike some other languages, Java’s String methods are called directly on String objects, and some operations (like join
) are static methods of the String class. For operations not directly available as methods (like count
), we’ve implemented a helper method to provide similar functionality.