Strings and regular expressions
String methods, String.format, StringBuilder, splitting, and regular expressions.
Runs in Zerethon IDE · Java 25
Official Java documentation ↗
Main.java
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
String name = "Ada Lovelace";
System.out.println(name.toUpperCase() + " " + name.length() + " " + name.substring(0, 3) + " " + name.indexOf("Love"));
System.out.println(" padded ".strip() + "|" + " " + name.contains("Love") + " " + "ada".equalsIgnoreCase("ADA"));
System.out.println(String.join("-", "a,b,c".split(",")) + " " + String.format("%.2f|%5d|%03d", 3.14159, 42, 7));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) sb.append(i).append(';');
System.out.println(sb.reverse());
Matcher m = Pattern.compile("order (\\d+) pending").matcher("Order 12 shipped, order 7 pending");
System.out.println(m.find() ? m.group(1) : "no match");
System.out.println("a1b22c".replaceAll("\\d+", "#"));
}
}
Output
ADA LOVELACE 12 Ada 4 padded| true true a-b-c 3.14| 42|007 ;2;1;0 7 a#b#c
- Strings are immutable; building a long string in a loop is faster with
StringBuilder. - In a Java string a regex backslash is written twice:
"\\d+". splittakes a regex: split on a dot withsplit("\\.").