Standard Library
class string
An immutable sequence of text, stored as UTF-8.
since 0.1.0-alpha.1linuxwindowswasm
Overview
Strings are values: no method changes the string it is called on, each returns a new one. A string literal is written with double quotes and supports ${expr} interpolation, so "n = ${n}" builds text without concatenation. + joins two strings and also converts the other operand to text when only one side is a string.
length, charAt, subStr, indexOf and byteAt count bytes, not characters, so they are exact for ASCII text and need care for anything else: "héllo" has six bytes but five characters. To work on characters (Unicode scalar values), call chars, which decodes the string into an Array<char>, or at, which decodes one character at a byte offset. Strings are not directly iterable with for; iterate s.chars().
Comparing strings with ==, <, >, <= and >= is byte-wise and lexicographic.
Description
A string is an immutable sequence of bytes, normally the UTF-8 encoding of text. It is a value type, the type of every string literal, and it defaults to "".
Two views of the same string coexist, and they are never mixed up:
- The byte view is the primary one.
length(),indexOf,subStr,charAtandbyteAtall count bytes and run in constant or linear time on the bytes."héllo".length()is6, becauseétakes two bytes. - The scalar view is opt-in.
chars()decodes the string into anArray<char>, one entry per Unicode scalar, andat(byteOffset)decodes the one scalar that starts at a byte offset."héllo".chars().length()is5.
A string is not iterable directly. Iterate its scalars with for (char c in s.chars()).
Bytes versus scalars
string s = "héllo";
console.writeln(s.length());
console.writeln(s.chars().length());
console.writeln(s.at(0));
console.writeln(s.at(1));
console.writeln(s.byteAt(1));
console.writeln(s.subStr(0, 3));
console.writeln("désert".reverse());
console.writeln(s.chars().joinToString("") == s);
try {
console.writeln(s.at(2));
} catch (RuntimeException e) {
console.writeln("caught: ${e.message}");
}
try {
console.writeln("abc".byteAt(5));
} catch (RuntimeException e) {
console.writeln("caught: ${e.message}");
}
6
5
h
é
195
hé
treséd
true
caught: byte offset 2 is not a scalar boundary
caught: index 5 out of bounds (length 3)
Rules
Indexing.
at(i)decodes the scalar that starts at byte offseti. An offset in the middle of a multi-byte sequence throws a catchableRuntimeException("not a scalar boundary").byteAt(i)returns the raw byte (0to255) at indexiand throws wheniis out of range. It does not returnNone.subStr(start, length)slices by bytes. Slicing through the middle of a multi-byte character produces a string with a broken sequence, so cut at scalar boundaries.reverse()reverses scalars, not bytes, so"désert".reverse()is"treséd"with the accent intact.std::byteToString(b)builds a one-byte string fromband throws for a value outside0..255.
Comparison.
==and!=compare contents.<,<=,>and>=are lexicographic: they compare the bytes in order. The empty string orders before every other string, and"Z" < "a"because uppercase ASCII comes first.
Parsing.
toInt()andtoFloat()return an optional,int?andfloat?, and never guess. The whole string must be a number: an optional leading-, then digits. Spaces, a leading+, trailing text and an out-of-range value all giveNone.toFloat()also givesNonefor non-finite spellings such as"inf"and"nan".- Narrow the result before using it, or default it:
int n = text.toInt() ?? 0;.
Decoding.
chars()andat()follow RFC 3629. They reject overlong encodings, surrogate code points, values aboveU+10FFFFand truncated sequences.- Ill-formed bytes never throw. Each ill-formed sequence decodes to one
U+FFFDreplacement character and decoding resumes at the first byte that broke the sequence. - For any well-formed string
s,s.chars().joinToString("") == s. - For byte-exact processing of data that may not be text, use
Blockinstead ofstring.
Examples
Ordering and parsing:
Comparing and parsing
console.writeln("apple" < "apricot");
console.writeln("" < "a");
console.writeln("Z" < "a");
console.writeln("abc" == "abc");
int? n = "-5".toInt();
console.writeln(n ?? 0);
console.writeln(" 12".toInt() == None);
console.writeln("+3".toInt() == None);
console.writeln("12x".toInt() == None);
console.writeln("99999999999999999999".toInt() == None);
console.writeln("2.5".toFloat());
console.writeln("inf".toFloat() == None);
true
true
true
true
-5
true
true
true
true
2.500000
true
Ill-formed bytes decode to the replacement character instead of failing:
Decoding ill-formed input
void show(string s) {
Array<char> cs = s.chars();
string codes = "";
for (char c in cs) {
codes = codes + c.code().toString() + " ";
}
console.writeln(codes.trim());
}
show("a\xC0\xAF");
show("\xE2\x82");
show("\xF0\x9D\x84\x9E");
show("\xED\xA0\x80");
97 65533 65533
65533
119070
65533 65533 65533
The first line is a followed by an overlong encoding of /, which yields two replacement characters. The second is a truncated sequence, which yields one. The third is a valid four-byte sequence, the single scalar U+1D11E. The fourth is an encoded surrogate, which is rejected byte by byte.
Notes
string has many more methods, such as split, replace, trim, padStart and repeat; they are listed in the library reference. For building a long string piece by piece, use StringBuilder.
Examples
Typical use
string line = " name = Ada Lovelace ";
string trimmed = line.trim();
int eq = trimmed.indexOf("=");
string key = trimmed.subStr(0, eq).trim();
string value = trimmed.subStr(eq + 1, trimmed.length() - eq - 1).trim();
console.writeln("${key} -> ${value}");
console.writeln(value.toUpper());
console.writeln(value.split(" ").length());
console.writeln("héllo".length());
console.writeln("héllo".chars().length());
name -> Ada Lovelace
ADA LOVELACE
2
6
5
Methods
at
at(int i) -> charDecode the character that starts at a byte offset.
The offset counts bytes, but the result is a whole character (a Unicode scalar value, a char), so at reads multi-byte characters correctly. The offset must be the first byte of a character: pointing into the middle of a multi-byte character throws, as does an offset outside the string. To get every character, use chars.
Parameters
- i
- The byte offset at which a character starts.
Returns
The char that starts at byte offset i.
Throws
RuntimeException- when
iis out of range or is not the start of a character.
Examples
string s = "héllo";
console.writeln(s.at(0));
console.writeln(s.at(1));
console.writeln(s.at(3));
try {
console.writeln(s.at(2));
} catch (RuntimeException e) {
console.writeln("caught: ${e.message}");
}
h
é
l
caught: byte offset 2 is not a scalar boundary
See also: chars, charAt, byteAt
byteAt
byteAt(int i) -> intThe raw byte value at a byte index, from 0 to 255.
Unlike charAt, an out-of-range index is an error, not an empty result. In non-ASCII text the bytes are the UTF-8 encoding: é is the two bytes 195 and 169.
Parameters
- i
- The zero-based byte index.
Returns
The byte at index i, as an int from 0 to 255.
Throws
RuntimeException- when
iis negative or not less thanlength().
Examples
console.writeln("A".byteAt(0));
console.writeln("héllo".byteAt(1));
console.writeln("héllo".byteAt(2));
try {
console.writeln("abc".byteAt(3));
} catch (RuntimeException e) {
console.writeln("caught: ${e.message}");
}
65
195
169
caught: index 3 out of bounds (length 3)
See also: charAt, at, byteToString
charAt
charAt(int i) -> stringThe single byte at a byte index, as a one-byte string.
The index counts bytes, not characters. For ASCII text the result is the character at that position. In non-ASCII text the index can fall inside a multi-byte character and the result is then an incomplete fragment; use at or chars to read whole characters. An index outside the string does not throw: the result is the empty string.
Parameters
- i
- The zero-based byte index.
Returns
A string of length 1, or "" if i is negative or not less than length().
Examples
string s = "hello";
console.writeln(s.charAt(0));
console.writeln(s.charAt(4));
console.writeln("[${s.charAt(5)}]");
console.writeln(s.charAt(1) + s.charAt(2));
h
o
[]
el
chars
chars() -> Array<char>Decode the string into an array of characters.
Each element is one Unicode scalar value, so the length of the array is the number of characters, not bytes. Bytes that are not valid UTF-8 never throw; each malformed sequence becomes the replacement character U+FFFD. Joining the characters back with joinToString("") gives the original string whenever it was valid UTF-8. A string is not directly iterable, so use this to loop over characters with for.
Returns
A new Array<char> holding the characters in order.
Examples
string s = "héllo";
Array<char> cs = s.chars();
console.writeln(cs.length());
console.writeln(s.length());
for (char c in cs) {
console.writeln(c.code());
}
5
6
104
233
108
108
111
See also: at, length, joinToString
contains
contains(string sub) -> boolTest whether sub occurs anywhere in the string.
The comparison is exact and case-sensitive. Every string contains the empty string.
Parameters
- sub
- The text to look for.
Returns
true if sub is found.
Examples
string s = "Hello, World";
console.writeln(s.contains("World"));
console.writeln(s.contains("world"));
console.writeln(s.contains(""));
true
false
true
See also: indexOf, startsWith, endsWith
count
count(string sub) -> intThe number of non-overlapping occurrences of a text.
Matches are counted from left to right and may not overlap, so "aaaa".count("aa") is 2. Counting the empty string gives 0.
Parameters
- sub
- The text to count.
Returns
The number of occurrences.
Examples
console.writeln("banana".count("an"));
console.writeln("aaaa".count("aa"));
console.writeln("abc".count("z"));
console.writeln("abc".count(""));
2
2
0
0
See also: indexOf, indexOfFrom
endsWith
endsWith(string suffix) -> boolTest whether the string ends with suffix.
The comparison is exact and case-sensitive. Every string ends with the empty string, and a suffix longer than the string never matches.
Parameters
- suffix
- The text the string should end with.
Returns
true if the last bytes of the string equal suffix.
Examples
string file = "report.txt";
console.writeln(file.endsWith(".txt"));
console.writeln(file.endsWith(".md"));
console.writeln("ab".endsWith("abc"));
true
false
false
See also: startsWith, removeSuffix, contains
equalsIgnoreCase
equalsIgnoreCase(string other) -> boolCompare two strings, ignoring the case of ASCII letters.
Only A to Z are folded to a to z; letters outside ASCII, such as É and é, are different characters here.
Parameters
- other
- The string to compare with.
Returns
true if the two strings are equal apart from ASCII letter case.
Examples
console.writeln("Hello".equalsIgnoreCase("hELLO"));
console.writeln("Hello".equalsIgnoreCase("Help"));
console.writeln("Hello".equalsIgnoreCase("Hello!"));
true
false
false
See also: toLower
ilike
ilike(string pattern) -> boolMatch the whole string against an SQL LIKE pattern, ignoring ASCII letter case.
The pattern language is the same as in like. Only the letters A to Z are folded.
Parameters
- pattern
- The pattern to match against.
Returns
true if the entire string matches pattern, ignoring ASCII case.
Examples
console.writeln("Hello".ilike("h%"));
console.writeln("Hello".like("h%"));
console.writeln("HELLO".ilike("h_llo"));
true
false
true
See also: like
indexOf
indexOf(string sub) -> intThe byte index of the first occurrence of sub, or -1 if it does not occur.
The index counts bytes from the start of the string, so after non-ASCII text it is larger than the number of characters before the match. Searching for the empty string finds 0. The search is exact and case-sensitive.
Parameters
- sub
- The text to look for.
Returns
The zero-based byte index of the first match, or -1.
Examples
string s = "Hello, World";
console.writeln(s.indexOf("o"));
console.writeln(s.indexOf("World"));
console.writeln(s.indexOf("xyz"));
console.writeln("héllo".indexOf("l"));
4
7
-1
3
See also: lastIndexOf, indexOfFrom, indexOfAny, contains
indexOfAny
indexOfAny(Array<string> needles) -> intThe byte index of the earliest position at which any of several strings occurs.
The result is the smallest index at which some needle starts, regardless of the order of the needles in the array. It does not say which needle matched. If no needle occurs, or the array is empty, the result is -1. An empty string among the needles matches at 0.
Parameters
- needles
- The strings to look for.
Returns
The lowest byte index at which any needle occurs, or -1.
Examples
string s = "Hello, World";
console.writeln(s.indexOfAny(["World", "o"]));
console.writeln(s.indexOfAny([",", "!"]));
console.writeln(s.indexOfAny(["z", "q"]));
Array<string> none = [];
console.writeln(s.indexOfAny(none));
4
5
-1
-1
indexOfFrom
indexOfFrom(string sub, int from) -> intThe byte index of the first occurrence of sub at or after a starting index.
Use it to find every match by searching again just past the previous one. The returned index is relative to the whole string, not to from. A negative from is treated as 0, and a from beyond the end finds nothing.
Parameters
- sub
- The text to look for.
- from
- The byte index at which to start searching.
Returns
The zero-based byte index of the first match at or after from, or -1.
Examples
string s = "a-b-c";
console.writeln(s.indexOfFrom("-", 0));
console.writeln(s.indexOfFrom("-", 2));
console.writeln(s.indexOfFrom("-", 4));
console.writeln(s.indexOfFrom("-", 99));
1
3
-1
-1
See also: indexOf, lastIndexOf, count
isBlank
isBlank() -> boolTest whether the string is empty or contains only whitespace.
Whitespace here means the same characters trim removes: space, tab, newline and carriage return.
Returns
true if nothing is left after trimming.
Examples
console.writeln("".isBlank());
console.writeln(" \t\n".isBlank());
console.writeln(" a ".isBlank());
true
true
false
isEmpty
isEmpty() -> boolTest whether the string has no bytes at all.
A string containing only spaces is not empty; see isBlank for that test.
Returns
true if length() is 0.
Examples
console.writeln("".isEmpty());
console.writeln(" ".isEmpty());
console.writeln("a".isEmpty());
true
false
false
See also: isBlank
lastIndexOf
lastIndexOf(string sub) -> intThe byte index of the last occurrence of sub, or -1 if it does not occur.
Where matches overlap, the last position at which sub starts is returned.
Parameters
- sub
- The text to look for.
Returns
The zero-based byte index of the last match, or -1.
Examples
string path = "a/b/c.txt";
int slash = path.lastIndexOf("/");
console.writeln(slash);
console.writeln(path.subStr(slash + 1, path.length() - slash - 1));
console.writeln(path.lastIndexOf("?"));
console.writeln("aaa".lastIndexOf("aa"));
3
c.txt
-1
1
See also: indexOf, indexOfFrom
length
length() -> intThe number of bytes in the string.
Strings are UTF-8, so the count is in bytes, not characters: an ASCII letter is one byte, but a letter such as é is two. To count characters use chars().length().
Returns
The byte length; 0 for the empty string.
Examples
console.writeln("hello".length());
console.writeln("".length());
console.writeln("héllo".length());
console.writeln("héllo".chars().length());
5
0
6
5
like
like(string pattern) -> boolMatch the whole string against an SQL LIKE pattern.
In the pattern % matches any run of bytes, including none, and _ matches exactly one byte. A backslash makes the next byte literal, so \% matches a percent sign; a lone backslash at the end of the pattern matches a backslash. The whole string must match, not just a part of it. Matching is case-sensitive (see ilike) and works on bytes, so one non-ASCII character counts as several _.
Parameters
- pattern
- The pattern to match against.
Returns
true if the entire string matches pattern.
Examples
console.writeln("hello".like("h%"));
console.writeln("hello".like("h_llo"));
console.writeln("hello".like("hell"));
console.writeln("Hello".like("h%"));
console.writeln("100%".like("100\\%"));
console.writeln("1000".like("100\\%"));
true
true
false
false
true
false
padEnd
padEnd(int targetLen, string pad) -> stringPad the end of the string until it reaches a length.
Copies of pad are added after the string, and the last copy is cut short if needed, so the result is exactly targetLen bytes long. A string that is already that long, or an empty pad, is returned unchanged. The length is counted in bytes.
Parameters
- targetLen
- The wanted length in bytes.
- pad
- The text to repeat as padding.
Returns
The padded string.
Examples
console.writeln("abc".padEnd(6, "."));
console.writeln("ab".padEnd(5, "xy"));
console.writeln("abcdef".padEnd(3, "."));
console.writeln("[" + "x".padEnd(4, " ") + "]");
abc...
abxyx
abcdef
[x ]
padStart
padStart(int targetLen, string pad) -> stringPad the start of the string until it reaches a length.
Copies of pad are added in front, and the last copy is cut short if needed, so the result is exactly targetLen bytes long. A string that is already that long, or an empty pad, is returned unchanged; the string is never shortened. The length is counted in bytes.
Parameters
- targetLen
- The wanted length in bytes.
- pad
- The text to repeat as padding.
Returns
The padded string.
Examples
console.writeln("5".padStart(3, "0"));
console.writeln("abc".padStart(8, "12"));
console.writeln("abc".padStart(2, "0"));
console.writeln("[" + "x".padStart(4, " ") + "]");
005
12121abc
abc
[ x]
removePrefix
removePrefix(string prefix) -> stringA copy without a leading prefix, if the string starts with it.
If the string does not start with prefix, it is returned unchanged. Only one copy of the prefix is removed.
Parameters
- prefix
- The text to remove from the start.
Returns
The string without prefix, or the original string.
Examples
console.writeln("prefix_name".removePrefix("prefix_"));
console.writeln("name".removePrefix("prefix_"));
console.writeln("xxy".removePrefix("x"));
name
name
xy
See also: removeSuffix, startsWith
removeSuffix
removeSuffix(string suffix) -> stringA copy without a trailing suffix, if the string ends with it.
If the string does not end with suffix, it is returned unchanged. Only one copy of the suffix is removed.
Parameters
- suffix
- The text to remove from the end.
Returns
The string without suffix, or the original string.
Examples
console.writeln("file.txt".removeSuffix(".txt"));
console.writeln("file.md".removeSuffix(".txt"));
console.writeln("yxx".removeSuffix("x"));
file
file.md
yx
See also: removePrefix, endsWith
repeat
repeat(int n) -> stringThe string joined to itself n times.
A count of zero or less gives the empty string.
Parameters
- n
- How many copies to join.
Returns
n copies of this, back to back.
Examples
console.writeln("ab".repeat(3));
console.writeln("-".repeat(10));
console.writeln("[" + "ab".repeat(0) + "]");
console.writeln("[" + "ab".repeat(-2) + "]");
ababab
----------
[]
[]
See also: padStart
replace
replace(string from, string to) -> stringA copy with every occurrence of one text replaced by another.
Matches are found from left to right and do not overlap, and replaced text is not searched again. If from is the empty string the original string is returned unchanged.
Parameters
- from
- The text to find.
- to
- The text to put in its place; may be empty to delete the matches.
Returns
The string with all non-overlapping occurrences of from replaced by to.
Examples
console.writeln("x-y-x".replace("x", "z"));
console.writeln("a.b.c".replace(".", ""));
console.writeln("aaa".replace("aa", "b"));
console.writeln("abc".replace("", "z"));
z-y-z
abc
ba
abc
See also: removePrefix, removeSuffix
reverse
reverse() -> stringA copy with the characters in reverse order.
The reversal works on characters, not bytes, so multi-byte characters stay intact. Bytes that are not valid UTF-8 are replaced by U+FFFD first, so reversing such a string is lossy.
Returns
The reversed string.
Examples
console.writeln("abc".reverse());
console.writeln("désert".reverse());
console.writeln("".reverse().isEmpty());
cba
treséd
true
See also: chars
split
split(string sep) -> Array<string>Cut the string into pieces at every occurrence of a separator.
The separator is not part of any piece. Empty pieces are kept: two separators in a row, or a separator at the start or end of the string, produce an empty string in the result. Splitting an empty string gives an array with one empty string. An empty separator cuts the string into one-byte strings.
Parameters
- sep
- The text that separates the pieces.
Returns
The pieces, in order. There is always at least one.
Examples
Array<string> parts = "a,b,,c".split(",");
console.writeln(parts.length());
for (string p in parts) {
console.writeln("[" + p + "]");
}
console.writeln("".split(",").length());
console.writeln("abc".split("").length());
4
[a]
[b]
[]
[c]
1
3
See also: splitLines, joinToString
splitLines
splitLines() -> Array<string>Split the text into lines.
Lines end at a newline (\n). One carriage return directly before the newline is dropped too, so Windows (\r\n) and Unix line endings both work. Spaces at the end of a line are kept. Text that ends with a newline produces a final empty line.
Returns
The lines, without their line endings.
Examples
Array<string> lines = "one\r\ntwo\nthree\r\n".splitLines();
console.writeln(lines.length());
for (string l in lines) {
console.writeln("[" + l + "]");
}
4
[one]
[two]
[three]
[]
startsWith
startsWith(string prefix) -> boolTest whether the string begins with prefix.
The comparison is exact and case-sensitive. Every string starts with the empty string.
Parameters
- prefix
- The text the string should begin with.
Returns
true if the first bytes of the string equal prefix.
Examples
string path = "/usr/local/bin";
console.writeln(path.startsWith("/usr"));
console.writeln(path.startsWith("usr"));
console.writeln(path.startsWith(""));
true
false
true
See also: endsWith, removePrefix, contains
subStr
subStr(int start, int len) -> stringA slice of the string: up to len bytes starting at byte start.
Both numbers count bytes. The slice never throws: if fewer than len bytes remain, the result stops at the end of the string, and a start that is negative or past the end gives "". Pass a non-negative len. When slicing non-ASCII text, make sure the slice does not start or end in the middle of a multi-byte character.
Parameters
- start
- The zero-based byte index of the first byte to include.
- len
- The number of bytes to take.
Returns
The slice, shorter than len bytes if the string ends first.
Examples
string s = "Hello, World";
console.writeln(s.subStr(7, 5));
console.writeln(s.subStr(0, 5));
console.writeln(s.subStr(7, 100));
console.writeln("[${s.subStr(100, 3)}]");
console.writeln("[${s.subStr(3, 0)}]");
World
Hello
World
[]
[]
See also: subStrRange, charAt, removePrefix
subStrRange
subStrRange(Range r) -> stringA slice of the string selected by a range of byte indices.
The range is inclusive at both ends, so 0..4 selects bytes 0 through 4, five bytes in all; it is the same as subStr(r.start, r.end - r.start + 1). An empty or backwards range gives "", and an end past the last byte stops at the end of the string. The indices are byte positions, not characters.
Parameters
- r
- The inclusive range of byte indices.
Returns
The selected slice.
Examples
string s = "Hello, World";
console.writeln(s.subStrRange(0..4));
console.writeln(s.subStrRange(7..11));
console.writeln(s.subStrRange(7..99));
console.writeln("[${s.subStrRange(4..2)}]");
Hello
World
World
[]
toFloat
toFloat() -> float | NoneParse the whole string as a decimal floating-point number.
The parse is strict, like toInt: the whole string must be a number, with no surrounding spaces. The text inf and nan are not accepted. A string that is not a finite number gives None. Give the result a default with ?? or test it against None before use.
Returns
The parsed float, or None if the string is not a valid finite number.
Examples
console.writeln("3.25".toFloat() ?? 0.0);
console.writeln("7".toFloat() ?? 0.0);
console.writeln("abc".toFloat() ?? 0.0);
console.writeln("inf".toFloat() ?? 0.0);
float? f = "2.5x".toFloat();
console.writeln(f == None);
3.250000
7.000000
0.000000
0.000000
true
See also: toInt
toInt
toInt() -> int | NoneParse the whole string as a decimal integer.
The parse is strict. The text must be an optional leading - followed by digits and nothing else: surrounding spaces, a leading +, an empty string, other characters, or a number too large for int all give None instead of a guess. Because the result is optional, give it a default with ?? or test it against None before use.
Returns
The parsed int, or None if the string is not a valid integer.
Examples
console.writeln("42".toInt() ?? 0);
console.writeln("-7".toInt() ?? 0);
console.writeln(" 42".toInt() ?? 0);
int? n = "4x".toInt();
if (n == None) {
console.writeln("not a number");
}
42
-7
0
not a number
See also: toFloat
toLower
toLower() -> stringA copy with every ASCII uppercase letter converted to lowercase.
Only the letters A to Z are changed. Characters outside ASCII, such as É, are left as they are.
Returns
The lowercased copy.
Examples
console.writeln("Hello, World".toLower());
console.writeln("CAFÉ".toLower());
hello, world
cafÉ
See also: toUpper, equalsIgnoreCase
toString
toString() -> stringThe string itself.
Present so that toString can be called on a value of any type, strings included.
Returns
this, unchanged.
Examples
string s = "hello";
console.writeln(s.toString());
console.writeln(s.toString() == s);
hello
true
toUpper
toUpper() -> stringA copy with every ASCII lowercase letter converted to uppercase.
Only the letters a to z are changed. Characters outside ASCII, such as é, are left as they are.
Returns
The uppercased copy.
Examples
console.writeln("Hello, World".toUpper());
console.writeln("route-66".toUpper());
console.writeln("café".toUpper());
HELLO, WORLD
ROUTE-66
CAFé
See also: toLower
trim
trim() -> stringA copy without leading and trailing whitespace.
The characters removed are the space, tab, newline (\n) and carriage return (\r). Whitespace in the middle of the string is kept. A string of only whitespace becomes "".
Returns
The trimmed copy.
Examples
string a = " hello world \n".trim();
console.writeln("[" + a + "]");
console.writeln("[" + " ".trim() + "]");
[hello world]
[]
See also: trimStart, trimEnd, isBlank
trimEnd
trimEnd() -> stringA copy without trailing whitespace.
Removes spaces, tabs, newlines and carriage returns from the end only; the start is left alone.
Returns
The string with its trailing whitespace removed.
Examples
string line = "total: 5 \r\n";
console.writeln("[" + line.trimEnd() + "]");
console.writeln(line.trimEnd().length());
console.writeln(line.length());
[total: 5]
8
12
trimStart
trimStart() -> stringA copy without leading whitespace.
Removes spaces, tabs, newlines and carriage returns from the start only; the end is left alone.
Returns
The string with its leading whitespace removed.
Examples
string s = " \thi there ";
console.writeln("[" + s.trimStart() + "]");
console.writeln("[" + s.trimEnd() + "]");
console.writeln("[" + s.trim() + "]");
[hi there ]
[ hi there]
[hi there]
See also
- StringBuilder — A mutable accumulator for building a string from many pieces.
- char — A single Unicode character, stored as one code point.
- String literals — Quoted strings, escapes,
${}interpolation, rawr"..."strings and triple-quoted multiline strings.