String Functions in Mercury

The standard library’s String class and StringUtils from Apache Commons Lang provide many useful string-related functions. Here are some examples to give you a sense of these utilities.

import org.apache.commons.lang3.StringUtils;

public class StringFunctions {
    // We create a shorthand for System.out.println as we'll use it a lot below.
    private static void p(String s) {
        System.out.println(s);
    }

    public static void main(String[] args) {
        // Here's a sample of the functions available for string manipulation.
        // Some of these are methods on the String object itself, while others
        // are static methods from the StringUtils class.

        p("Contains:  " + "test".contains("es"));
        p("Count:     " + StringUtils.countMatches("test", "t"));
        p("HasPrefix: " + "test".startsWith("te"));
        p("HasSuffix: " + "test".endsWith("st"));
        p("Index:     " + "test".indexOf("e"));
        p("Join:      " + String.join("-", "a", "b"));
        p("Repeat:    " + StringUtils.repeat("a", 5));
        p("Replace:   " + "foo".replace("o", "0"));
        p("Replace:   " + "foo".replaceFirst("o", "0"));
        p("Split:     " + String.join(", ", "a-b-c-d-e".split("-")));
        p("ToLower:   " + "TEST".toLowerCase());
        p("ToUpper:   " + "test".toUpperCase());
    }
}

When you run this program, you’ll see:

$ javac -cp commons-lang3-3.12.0.jar StringFunctions.java
$ java -cp .:commons-lang3-3.12.0.jar 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

Note that for this example to work, you’ll need to have the Apache Commons Lang library in your classpath. You can download it from the Apache Commons website or use a build tool like Maven or Gradle to manage the dependency.

In Java, many string operations are methods on the String object itself, which is different from the Go approach of having a separate strings package. However, for some more complex operations, we’ve used the StringUtils class from Apache Commons Lang, which provides functionality similar to Go’s strings package.