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: TESTIn 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:
- Java doesn’t have a direct equivalent of Go’s
strings.Count(), so we used a stream to count occurrences. HasPrefixandHasSuffixare calledstartsWithandendsWithin Java.- Java’s
replacemethod replaces all occurrences by default, so we usedreplaceFirstto show the equivalent of Go’sReplacewith a count of 1. - We used
String.join()as a static method, unlike Go’sstrings.Join(). Arrays.toString()is used to print the result ofsplit()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.
Comments powered by Disqus