String Functions in Fortress

The standard library’s String class and java.util.Arrays class provide many useful string-related functions. Here are some examples to give you a sense of these operations.

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

    public static void main(String[] args) {
        // Here's a sample of the functions available for Strings.
        // Since these are methods on the String object itself,
        // we can 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".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());
    }
}

When you run this program, you’ll get:

$ 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 of the String class to perform operations similar to those in the original example. Some differences to note:

  1. Java doesn’t have a direct equivalent of Go’s strings.Count(), so we used a stream to count occurrences.
  2. HasPrefix and HasSuffix are called startsWith and endsWith in Java.
  3. Java’s replace method replaces all occurrences by default, so we used replaceFirst to show the equivalent of Go’s Replace with a count of 1.
  4. We used String.join() as a static method, unlike Go’s strings.Join().
  5. Arrays.toString() is used to print the result of split() in a readable format.

These examples demonstrate some of the common string operations in Java. Remember to refer to the Java documentation for a complete list of available string methods and their usage.