String Functions in R Programming Language

The standard library’s stringr package provides many useful string-related functions. Here are some examples to give you a sense of the package.

library(stringr)

# We create a simple print function to mimic the Go example
p <- function(...) {
  cat(paste0(..., "\n"))
}

# Here's a sample of the functions available in stringr.
# Note that in R, these are typically used as functions
# that take the string as the first argument, similar to
# the Go example.

p("Contains:  ", str_detect("test", "es"))
p("Count:     ", str_count("test", "t"))
p("HasPrefix: ", str_starts("test", "te"))
p("HasSuffix: ", str_ends("test", "st"))
p("Index:     ", str_locate("test", "e")[1])
p("Join:      ", str_c(c("a", "b"), collapse = "-"))
p("Repeat:    ", str_dup("a", 5))
p("Replace:   ", str_replace_all("foo", "o", "0"))
p("Replace:   ", str_replace("foo", "o", "0"))
p("Split:     ", str_split("a-b-c-d-e", "-", simplify = TRUE))
p("ToLower:   ", str_to_lower("TEST"))
p("ToUpper:   ", str_to_upper("test"))

This script demonstrates various string manipulation functions in R using the stringr package. Here’s a breakdown of what each function does:

  • str_detect(): Checks if a string contains a pattern
  • str_count(): Counts occurrences of a pattern in a string
  • str_starts(): Checks if a string starts with a pattern
  • str_ends(): Checks if a string ends with a pattern
  • str_locate(): Finds the position of a pattern in a string
  • str_c(): Concatenates strings
  • str_dup(): Duplicates strings
  • str_replace_all(): Replaces all occurrences of a pattern in a string
  • str_replace(): Replaces the first occurrence of a pattern in a string
  • str_split(): Splits a string into a vector
  • str_to_lower(): Converts a string to lowercase
  • str_to_upper(): Converts a string to uppercase

When you run this script, you’ll see output similar to the following:

Contains:   TRUE
Count:      2
HasPrefix:  TRUE
HasSuffix:  TRUE
Index:      2
Join:       a-b
Repeat:     aaaaa
Replace:    f00
Replace:    f0o
Split:      a b c d e
ToLower:    test
ToUpper:    TEST

This demonstrates how to perform common string operations in R using the stringr package, which provides a consistent and intuitive interface for string manipulation.