String
import "std/types" (included in import "std") · namespace std.types
String makes Str's text functions methods of any string (s.trim() is String.trim(s) is Str.trim(s)), and adds conversions to numbers and other types, characters (UTF-8 aware), and natural order.
grav
import "std"
fn main() {
let s = " Hello, World "
print(s.trim().lower())
print("user_name".toCamelCase() + " " + "grav".reverse() + " " + "ab".padLeft(4, "."))
print("${"42".toInt() + 1} ${"19.99".toDecimal() * 3} ${"né".charCount()} ${"né".length}")
print("{0} has {1} stars".format(["grav", 42]))
let files: Array<string> = ["file10", "file2", "file1"]
files.sortBy(String.compareNatural)
print(files)
}hello, world
userName varg ..ab
43 59.97 2 3
grav has 42 stars
["file1", "file2", "file10"]s.lengthcounts bytes;charCount()counts characters, andchars()splits into them."42" as int,"2.5" as float,"yes" as booland"19.99" as Decimalconvert liketoInt()and the rest, with aValueErrorfor text that is not one.
API
class String
Text (see the top of this file).
Static members
static fn length(s: string) -> int— The length in bytes (UTF-8: a character may take several).static fn isEmpty(s: string) -> bool— Whether the string is "".static fn isBlank(s: string) -> bool— Empty or only whitespace.static fn equals(a: string, b: string) -> bool— Whether the strings have the same contents (same as ==).static fn equalsIgnoreCase(a: string, b: string) -> bool— Whether the strings are equal ignoring ASCII letter case.static fn compare(a: string, b: string) -> int— <0, 0, >0 like strcmp:xs.sortBy(fn(a, b) => Str.compare(a, b))sorts A-Z.static fn compareIgnoreCase(a: string, b: string) -> int— Like compare, ignoring ASCII letter case.static fn charAt(s: string, i: int) -> int— The byte at index i (bounds-checked).static fn isDigits(s: string) -> bool— Whether every character is a digit 0-9 (false for "").static fn isAlpha(s: string) -> bool— Whether every character is an ASCII letter (false for "").static fn isAlphanumeric(s: string) -> bool— Whether every character is an ASCII letter or digit (false for "").static fn isUpper(s: string) -> bool— Whether no letter is lowercase (false for "").static fn isLower(s: string) -> bool— Whether no letter is uppercase (false for "").static fn indexOf(s: string, sub: string) -> int— The byte index of the first occurrence ofsub, or -1.static fn indexFrom(s: string, sub: string, from: int) -> int— The byte index of the first occurrence ofsubat or afterfrom, or -1.static fn lastIndexOf(s: string, sub: string) -> int— The byte index of the last occurrence ofsub, or -1.static fn contains(s: string, sub: string) -> bool— Whethersuboccurs in the string.static fn count(s: string, sub: string) -> int— How many non-overlapping timessuboccurs (0 for an emptysub).static fn startsWith(s: string, prefix: string) -> bool— Whether the string begins withprefix.static fn endsWith(s: string, suffix: string) -> bool— Whether the string ends withsuffix.static fn concat(a: string, b: string) -> string— The two strings joined (same as a + b).static fn upper(s: string) -> string— ASCII letters made uppercase.static fn lower(s: string) -> string— ASCII letters made lowercase.static fn capitalize(s: string) -> string— The first character made uppercase (ASCII).static fn reverse(s: string) -> string— The bytes in reverse order.static fn repeat(s: string, n: int) -> string— The string repeated n times ("" for n <= 0).static fn substring(s: string, start: int, len: int) -> string—lenbytes starting atstart(bounds are clamped).static fn slice(s: string, start: int, end: int) -> string— Characters [start, end) (bounds are clamped).static fn remove(s: string, start: int, len: int) -> string— The string without thelenbytes starting atstart.static fn removePrefix(s: string, prefix: string) -> string— The string withoutprefixat its start (unchanged when it does not start with it).static fn removeSuffix(s: string, suffix: string) -> string— The string withoutsuffixat its end (unchanged when it does not end with it).static fn trim(s: string) -> string— Without whitespace at both ends.static fn trimStart(s: string) -> string— Without whitespace at the start.static fn trimEnd(s: string) -> string— Without whitespace at the end.static fn replace(s: string, old: string, repl: string) -> string— Every occurrence ofoldreplaced byrepl.static fn padLeft(s: string, len: int, ch: string) -> string— Pad tolencharacters with the first character ofch(a space ifchis empty).static fn padRight(s: string, len: int, ch: string) -> string— Padded on the right tolencharacters with the first character ofch(a space if empty).static fn center(s: string, width: int, ch: string) -> string— Centered inwidthcharacters, padded with the first character ofch(a space if empty).static fn split(s: string, delim: string) -> Array<string>— The parts between occurrences ofdelim("a,,b" by "," gives "a", "", "b").static fn lines(s: string) -> Array<string>— Lines of text (handles \n and \r\n; no trailing empty line for a final newline).static fn words(s: string) -> Array<string>— Whitespace-separated words (no empty entries).static fn replaceFirst(s: string, old: string, repl: string) -> string—swith only the first occurrence ofoldreplaced.static fn splitN(s: string, delim: string, limit: int) -> Array<string>— Split atdeliminto at mostlimitpieces (the last keeps the rest): splitN("a=b=c", "=", 2) == ["a", "b=c"].static fn before(s: string, sep: string) -> string— The text before the firstsep, or all ofswhen it does not contain one.static fn after(s: string, sep: string) -> string— The text after the firstsep, or "" when it does not contain one.static fn truncate(s: string, max: int) -> string— At mostmaxcharacters, ending in "…" when it was cut.static fn wrap(s: string, width: int) -> Array<string>— The words ofsre-flowed into lines of at mostwidthcharacters (a longer word gets a line of its own).static fn indent(s: string, prefix: string) -> string— Each line ofsprefixed withprefix.static fn identifierWords(s: string) -> Array<string>— The words of an identifier or phrase: "parseHTTPRequest", "parse_http request" and "parse-http" all split into lowercase words.static fn toSnakeCase(s: string) -> string— snake_case: "parseHttpRequest" -> "parse_http_request".static fn toKebabCase(s: string) -> string— kebab-case: "parseHttpRequest" -> "parse-http-request".static fn toCamelCase(s: string) -> string— camelCase: "parse_http_request" -> "parseHttpRequest".static fn toPascalCase(s: string) -> string— PascalCase: "parse_http_request" -> "ParseHttpRequest".static fn titleCase(s: string) -> string— Every word capitalized: "the grav book" -> "The Grav Book".static fn levenshtein(a: string, b: string) -> int— The number of single-character edits (insert, delete, replace) that turn a into b, counted in bytes: levenshtein("kitten", "sitting") == 3.static fn commonPrefix(a: string, b: string) -> string— The longest start that a and b share.static fn startsWithIgnoreCase(s: string, prefix: string) -> bool— Whethersstarts withprefix, ignoring case.static fn containsIgnoreCase(s: string, sub: string) -> bool— Whetherscontainssub, ignoring case.static fn descending(a: string, b: string) -> int— Comparators for sorting (names.sortBy(String.compare), also compareIgnoreCase above): byte order, -1, 0 or 1.static fn compareTo(a: string, b: string) -> int—a.compareTo(b): as compare.static fn compareNatural(a: string, b: string) -> int— Natural order: runs of digits compare as numbers ("file2" before "file10").static fn toInt(s: string) -> int— The text as an int, a long, a float, a Decimal or a bool; ValueError when it is not one.static fn toLong(s: string) -> longstatic fn toFloat(s: string) -> floatstatic fn toDecimal(s: string) -> Decimalstatic fn toBool(s: string) -> boolstatic fn isInteger(s: string) -> bool— Whether all of it is a whole number, or any number.static fn isNumber(s: string) -> boolstatic fn toBytes(s: string) -> Bytes— Its UTF-8 bytes.static fn chars(s: string) -> Array<string>— Its characters (UTF-8 aware: "né" gives ["n", "é"]).static fn charCount(s: string) -> int— How many characters it has (UTF-8 aware;s.lengthcounts bytes).static fn format(s: string, args: Array<any>) -> string—swith "{0}", "{1}", ... replaced byargs("{0} is {1}" with ["x", 3] is "x is 3").