Working with text
Ring has good text functions of its own. This lesson shows what Java adds: String methods, StringBuilder, String.format, regular expressions and Unicode.
What you will learn#
- which jobs Ring does by itself and which need Java,
Stringmethods and static helpers,StringBuilderfor long texts,- regular expressions with
PatternandMatcher, - Unicode: Ring text is UTF-8, Java text is UTF-16, and the conversion is automatic.
The program#
# Tutorial 2: text - String, StringBuilder, String.format and regular expressions
load "java.ring"
using {
"java.lang"
"java.util.regex"
}
Pattern = new Pattern
cSentence = " Ring meets Java, and Java meets Ring "
# Ring first: the basics are Ring functions
? upper(trim(cSentence))
# a Java String object has all the methods of Java
oText = new String(trim(cSentence))
? oText.length()
? oText.toLowerCase()
? oText.indexOf("Java")
? oText.contains("meets")
? oText.replace("Java","Kotlin")
? oText.startsWith("Ring")
? oText.substring([5,10])
# static helpers: no object is needed
? String.join("-",["a","b","c"])
? String.format(["%s has %d letters and costs %.2f",["Ring",4,9.5]])
? String.valueOf(2.5)
# StringBuilder grows in place: use it for long texts
oSB = new StringBuilder
for nI = 1 to 5
oSB.append(nI).append(",")
next
oSB.setLength(oSB.length() - 1)
? oSB.toString()
? oSB.reverse().toString()
# regular expressions: Pattern and Matcher
oPattern = Pattern.compile("[a-z]+@[a-z]+\.com")
oMatcher = oPattern.matcher("mail ann@site.com or bob@work.com today")
while oMatcher.find()
? "found: " + oMatcher.group()
end
? Pattern.matches("^[0-9]+$","12345")
? Pattern.matches("^[0-9]+$","12x45")
? oText.replaceAll("[aeiou]","*")
# Unicode: Ring text is UTF-8, Java text is UTF-16, the conversion is automatic
oArabic = new String("مرحبا")
? oArabic.length()
? oArabic.toUpperCase()RING MEETS JAVA, AND JAVA MEETS RING
36
ring meets java, and java meets ring
11
1
Ring meets Kotlin, and Kotlin meets Ring
1
meets
a-b-c
Ring has 4 letters and costs 9.50
2.5
1,2,3,4,5
5,4,3,2,1
found: ann@site.com
found: bob@work.com
1
0
R*ng m**ts J*v*, *nd J*v* m**ts R*ng
5
مرحباHow it works#
A Ring text becomes a Java String when it goes to a Java method, and a Java String that a method returns is a Ring text. A text is therefore not an object in Ring: use Ring's own trim(), upper(), substr() for the basics. When you need the Java methods of a String, create one with new String("text"); that object has all of them.
String.format("%s has %d items", ...) and String.join(",", list) are static helpers: no object is needed. StringBuilder grows in place, so use it to build a long text in a loop.
A regular expression is a pattern for text. Pattern.compile("[0-9]+") makes the pattern, matcher(text) searches a text, and find() moves from match to match.
Exercises#
- Find every number in
"3 cats and 12 fish"with a pattern. - Use
String.formatto printAnn is 31 years old. - Reverse a text with
StringBuilder.reverse().