Basics, 4 of 8
Strings and Char
Interpolation and format specs, String's Methods, characters, and raw and multi-line strings.
What you’ll build
A program that reports on a line of text: it tidies the line, counts its words, puts it in title
case, and lays out a small table. A String is text, and a Char is one character of it.
Putting values in strings
Braces in a string hold any expression, whose value is put in its place. + joins two strings.
A backslash starts an escape, like \" for a quote or \n for a line break, and {{ and }} are
literal braces.
Import std.core
Local name = "fox"
Local legs = 4
Print("The {name} has {legs} legs, {legs * 2} with a friend.")
Print("Say \"hi\"" + " to the " + name + ".")
Print("Braces: {{like this}}")The fox has 4 legs, 8 with a friend.
Say "hi" to the fox.
Braces: {like this}+ only joins a String to a String; anything else goes in braces.
Format specs
After a colon inside the braces, a format spec says how to write the value: <, >, or ^ and a
width pad it on the right, left, or both sides; .2 gives two digits after the point; ,
groups digits in thousands; and % writes a fraction as a percentage.
Import std.core
Local items = ["apples", "pears", "figs"]
Local prices = [1.5, 12.25, 120.0]
For i, item In items
Print("{item:<8}|{prices[i]:>8.2}|")
End For
Print("{1234567:,} {0.075:.1%} {7:03}")apples | 1.50| pears | 12.25| figs | 120.00| 1,234,567 7.5% 007
For i, item In items gives each element with its index.
String’s Methods
A String’s Methods, the functions called on a String with a dot, come from std.text, so a file
that uses them imports it. Trim takes off
the spaces at both ends, Split cuts the text at a separator, and Find gives the position of
some text, or Null when it isn’t there. A String never changes: a Method that changes text, like Trim or Replace, gives a new
String.
Import std.core
Import std.text
Local line = " the QUICK brown fox jumps over the lazy dog "
Local text = line.Trim()
Local words = text.Split(" ")
Print("\"{text}\"")
Print("{words.Count} words; the third is \"{words[2]}\", {words[2].Length} letters")
Print(text.ToLower())
Print("fox at {text.Find("fox") ?? -1}, cat at {text.Find("cat") ?? -1}")
Print(text.Replace("lazy", "sleepy"))"the QUICK brown fox jumps over the lazy dog" 9 words; the third is "brown", 5 letters the quick brown fox jumps over the lazy dog fox at 16, cat at -1 the QUICK brown fox jumps over the sleepy dog
?? -1 gives -1 when Find gives Null. Nullable types
explains ??.
Characters
A Char is one Unicode character, written in single quotes, like 'a'. A string’s Chars is an
array of its characters, and a Char has Methods such as IsLetter and ToUpper. A
StringBuilder builds a string a piece at a time.
Import std.core
Import std.text
Function TitleCase(text: String): String
Local out = StringBuilder()
Local start = True
For c In text.Chars
If c.IsLetter()
out.Append(start ? c.ToUpper() : c.ToLower())
start = False
Else
out.Append(c)
start = True
End If
End For
Return out.ToString()
End Function
Print(TitleCase("the QUICK brown fox"))
Print("naïve".Length, "naïve".CharCount)The Quick Brown Fox 6 5
A String is stored as UTF-8, and its Length counts bytes: ï takes two, so “naïve” has a
Length of 6 and a CharCount of 5. Positions, like what Find gives, are byte positions too.
There’s no text[i], since finding the i-th character means reading from the start; go through
Chars instead.
Raw and multi-line strings
A raw string, r"...", has no escapes or interpolation, which suits paths and patterns. Three
quotes start a string of several lines. The closing quotes’ indentation is taken off every line,
so the string can be indented with the code around it.
Import std.core
Local folder = r"C:\reports\new"
Local animal = "fox"
Local note = """
Report on the {animal}:
- quick
- brown
"""
Print(folder)
Print(note)C:\reports\new Report on the fox: - quick - brown
What you learned
"{expr}"puts a value in a string, and a format spec after a colon lays it out.+joins Strings only; everything else goes in braces.- String’s Methods come from std.text, and the ones that change text give a new String, since a String never changes.
- A
Charis one character;Charsgives a String’s characters, andLengthcounts its bytes. r"..."is a raw string, and"""starts one of several lines.
The rules are in the language reference.
Report an issue with this page or with FutureBlitz on GitHub.