字符串操作
8 methods用于测量、切片和替换变量中文本的 Bash 参数展开运算符。
str_length(string) -> integer返回变量值的字符长度。
Parameters
| Name | Type | Description |
|---|---|---|
| string | character | Input character vector. |
Returns
integer
Example
r
library(stringr)
str_length(c("hello", "café", "")) # 5 4 0str_sub(string, start = 1L, end = -1L) -> character从 offset(从 0 开始)处提取指定长度的子字符串。省略 length 则提取到末尾。
Parameters
| Name | Type | Description |
|---|---|---|
| offset | character | 起始位置(负数从末尾开始计数)。 |
| length | integer | 字符数(可选)。 |
| end | integer | End position (default -1 = last char). |
Returns
character
Example
r
library(stringr)
str_sub("Hello, World", 8) # "World"
str_sub("Hello, World", 8, 12) # "World"
str_sub("Hello", -3) # "llo"str_detect(string, pattern) -> logical将 var 值中 old(glob 模式)的第一个匹配项替换为 new。
Parameters
| Name | Type | Description |
|---|---|---|
| old | character | 要匹配的 glob 模式。 |
| new | character|regex | 替换字符串。 |
Returns
logical
Example
r
library(stringr)
str_detect(c("apple", "banana", "cherry"), "^a") # TRUE FALSE FALSE
str_detect(c("cat", "dog"), "a") # TRUE FALSEstr_replace(string, pattern, replacement) -> character将 var 值中 old(glob 模式)的所有匹配项替换为 new。
Parameters
| Name | Type | Description |
|---|---|---|
| old | character | 要匹配的 glob 模式。 |
| new | character|regex | 替换字符串。 |
| replacement | character | Replacement string. |
Returns
character
Example
r
library(stringr)
str_replace("Hello, World", "World", "R") # "Hello, R"
# Use str_replace_all for all matches
str_replace_all("a-b-c", "-", "_") # "a_b_c"str_to_lower(string) -> character从 var 值的开头移除 prefix 的最短匹配项。
Parameters
| Name | Type | Description |
|---|---|---|
| prefix | character | 要从开头移除的 glob 模式。 |
Returns
character
Example
r
library(stringr)
str_to_lower("HELLO World") # "hello world"str_split(string, pattern) -> list从 var 值的末尾移除 suffix 的最短匹配项。
Parameters
| Name | Type | Description |
|---|---|---|
| suffix | character | 要从末尾移除的 glob 模式。 |
| pattern | character|regex | Split pattern. |
Returns
list
Example
r
library(stringr)
str_split("a,b,c", ",")
# [[1]]
# [1] "a" "b" "c"
str_split(c("a-b", "c-d-e"), "-")str_c(..., sep = "") -> character返回 var 转换为大写后的值。需要 Bash 4.0+。
Parameters
| Name | Type | Description |
|---|---|---|
| ... | character | Strings to concatenate. |
| sep | character | Separator between inputs (default empty). |
Returns
character
Example
r
library(stringr)
str_c("Hello", "World", sep = ", ") # "Hello, World"
str_c(c("a", "b"), c("1", "2")) # "a1" "b2"str_trim(string, side = c("both", "left", "right")) -> character返回 var 转换为小写后的值。需要 Bash 4.0+。
Parameters
| Name | Type | Description |
|---|---|---|
| string | character | Input character vector. |
| side | character | Which side(s) to trim (default both). |
Returns
character
Example
r
library(stringr)
str_trim(" hello ") # "hello"
str_trim(" hello ", "left") # "hello "
str_trim(" hello ", "right") # " hello"