Strings
paste and sprintf, nchar, substr, toupper, strsplit, and regular expressions with grepl, sub, gsub and regmatches.
Runs in Zerethon IDE · R 4.5
Official R documentation ↗
main.R
name <- "Ada Lovelace"
cat(sprintf("%s has %d characters\n", name, nchar(name)))
writeLines(c(toupper(name), tolower(name), substr(name, 1, 3)))
writeLines(paste0(trimws(" padded "), "|"))
print(strsplit("a,b,c", ",")[[1]])
writeLines(paste(c("x", "y", "z"), collapse = "-"))
writeLines(sub("Ada", "Augusta", name))
print(c(startsWith(name, "Ada"), grepl("love", name, ignore.case = TRUE)))
cat(sprintf("%.2f %5d %03d\n", 3.14159, 42L, 7L))
text <- "Order 12 shipped, order 7 pending"
print(as.numeric(regmatches(text, gregexpr("[0-9]+", text))[[1]]))
print(as.numeric(sub(".*order ([0-9]+) pending.*", "\\1", text)))
Output
Ada Lovelace has 12 characters ADA LOVELACE ada lovelace Ada padded| [1] "a" "b" "c" x-y-z Augusta Lovelace [1] TRUE TRUE 3.14 42 007 [1] 12 7 [1] 7
paste()joins with a space,paste0()with nothing;collapse =joins the elements of one vector.strsplit()returns a list (one entry per input string) — take[[1]]for the first.- Regular expressions are written as strings, so a backslash is doubled:
"\\d+". sub()replaces the first match,gsub()every match.