Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

R 字符串


字符串字面量

字符串用于存储文本。

字符串用单引号或双引号括起来

"hello"'hello' 相同

示例

"hello"
'hello'
自己尝试 »

将字符串赋值给变量

将字符串赋值给变量是通过变量后跟 <- 运算符和字符串来完成的

示例

str <- "Hello"
str # 打印 str 的值
自己尝试 »

多行字符串

您可以像这样将多行字符串赋值给变量

示例

str <- "Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."

str # 打印 str 的值
自己尝试 »

但是,请注意,R 会在每个换行符的末尾添加一个“\n”。这称为转义字符,而n字符表示换行

如果希望换行符与代码中的位置相同,请使用 cat() 函数

示例

str <- "Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."

cat(str)
自己尝试 »


字符串长度

R 中有很多有用的字符串函数。

例如,要查找字符串中的字符数,请使用 nchar() 函数

示例

str <- "Hello World!"

nchar(str)
自己尝试 »

检查字符串

使用 grepl() 函数检查字符串中是否存在字符或字符序列

示例

str <- "Hello World!"

grepl("H", str)
grepl("Hello", str)
grepl("X", str)
自己尝试 »

合并两个字符串

使用 paste() 函数合并/连接两个字符串

示例

str1 <- "Hello"
str2 <- "World"

paste(str1, str2)
自己尝试 »


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.