String Functions in Karel

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 o) {
        System.out.println(o);
    }

    public static void main(String[] args) {
        // Here's a sample of the methods available in the String class.
        // 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 Java String class documentation.

        p("Contains:  " + "test".contains("es"));
        p("Count:     " + countOccurrences("test", 't'));
        p("StartsWith: " + "test".startsWith("te"));
        p("EndsWith: " + "test".endsWith("st"));
        p("IndexOf:     " + "test".indexOf("e"));
        p("Join:      " + String.join("-", "a", "b"));
        p("Repeat:    " + "a".repeat(5));
        p("Replace:   " + "foo".replace("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());
    }

    // 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:

$ java StringFunctions
Contains:   true
Count:      2
StartsWith: true
EndsWith: true
IndexOf:     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 in some other languages, Java strings are immutable, so methods like replace and toLowerCase return new String objects rather than modifying the original.

The String class in Java provides many useful methods for string manipulation. Some methods, like contains, startsWith, endsWith, work similarly to their counterparts in other languages. Others, like replace, work slightly differently - in Java, you specify the old and new characters or substrings, rather than providing a count of replacements.

Java doesn’t have a built-in count method for strings, so we’ve implemented a simple one using streams. For more complex string operations, you might want to look into the Pattern and Matcher classes in the java.util.regex package.

Remember, in Java, strings are objects, so these operations are methods called on String objects, rather than functions that take strings as arguments.