字符串处理函数
本课属于 Coddy R 学习旅程的“基础知识”单元。第 66 课,共 78 课。
现在你已经知道如何将字符串拆分为字符,接下来我们来了解几个在 R 中处理字符串的基本函数。这些函数可以帮助你测量、合并和转换文本数据。
nchar() 函数会返回字符串中的字符数:
word <- "hello"
print(nchar(word))输出:
[1] 5要将多个字符串合并成一个,请使用 paste()。默认情况下,它会用空格分隔各个元素:
result <- paste("Hello", "World")
print(result)输出:
[1] "Hello World"当你不想在字符串之间添加分隔符时,使用 paste0():
result <- paste0("Hello", "World")
print(result)输出:
[1] "HelloWorld"对于大小写转换,R 提供了 toupper() 和 tolower():
print(toupper("hello"))
print(tolower("WORLD"))输出:
[1] "HELLO"
[1] "world"将这些函数与你学过的迭代技巧结合起来,就能发挥强大的作用,让你逐个字符或以整个字符串为单位处理和转换文本。
挑战
简单你会收到两行输入:
- 名(例如,
john) - 姓(例如,
SMITH)
执行以下操作:
- 使用
toupper()将名转换为大写 - 使用
tolower()将姓转换为小写 - 使用
paste()将它们合并为全名(中间加一个空格) - 使用
nchar()计算全名中的字符总数(包括空格) - 使用
paste0()将名和姓合并,中间不加分隔符,创建用户名,并将所有字母转换为小写 - 打印全名
- 打印字符数
- 打印用户名
例如,如果输入为:
alice
WONDER输出应为:
[1] "ALICE wonder"
[1] 12
[1] "alicewonder"说明:名 "alice" 会变为 "ALICE"(大写),姓 "WONDER" 会变为 "wonder"(小写)。全名 "ALICE wonder" 有 12 个字符(包括空格)。用户名将名和姓都转换为小写后合并,中间不加分隔符:"alicewonder"。
亲手试试
# 读取输入
con <- file("stdin", "r")
first_name <- suppressWarnings(readLines(con, n = 1))
last_name <- suppressWarnings(readLines(con, n = 1))
close(con)
# TODO: 在下方编写你的代码
# 1. 使用 toupper() 将 first_name 转为大写
# 2. 使用 tolower() 将 last_name 转为小写
# 3. 使用 paste() 将它们合并为 full_name
# 4. 使用 nchar() 计算字符数
# 5. 使用 paste0() 创建 username(全部小写)
# 输出结果
print(full_name)
print(char_count)
print(username)这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: R 在线编译器