←
PDF 242 / 520 Exercises
→
English · PDF 242
Original PDF page 242
中文 · PDF 242

练习

    1. 将字符串中的所有正斜杠替换为反斜杠。
    1. 使用 replace_all() 实现一个简单版本的 str_to_lower()。
    1. 交换单词的首字母和末字母。其中哪些字符串仍然是单词?

拆分

使用 str_split() 将字符串拆分成多个片段。例如,我们可以将句子拆分成单词:

sentences %>% head(5) %>% str_split(" ") #> [[1]] #> [1] "The" "birch" "canoe" "slid" "on" "the" #> [7] "smooth" "planks." #> #> [[2]] #> [1] "Glue" "the" "sheet" "to" #> [5] "the" "dark" "blue" "background." #> #> [[3]] #> [1] "It's" "easy" "to" "tell" "the" "depth" "of" #> [8] "a" "well." #> #> [[4]] #> [1] "These" "days" "a" "chicken" "leg" "is" #> [7] "a" "rare" "dish." #> #> [[5]] #> [1] "Rice" "is" "often" "served" "in" "round" #> [7] "bowls."

因为每个元素可能包含不同数量的片段,所以该函数返回一个列表。如果你处理的是长度为 1 的向量,最简单的方法就是直接提取列表的第一个元素:

"a|b|c|d" %>% str_split("\|") %>% .[[1]] #> [1] "a" "b" "c" "d"

否则,与其他返回列表的 stringr 函数一样,你可以使用 simplify = TRUE 来返回一个矩阵: