R语言 字符串连接
字符串连接是将两个或多个字符串附加到一个字符串中的方法,无论是逐个字符还是使用一些特殊的字符结尾。有很多方法可以进行字符串连接。
例子
Input: str1 = ‘Geeks’
str2 = ‘for’
str3 = ‘Geeks’
Output: ‘GeeksforGeeks’
为了在R中进行连接,我们使用paste()函数,它可以将两个或多个字符串结合在一起。它接受不同类型的参数,如下所示。
语法:
paste(string1, string2, ….stringn, sep = “”, collapse=NULL)
参数:
string1, string2…string3: 为连接提供的字符串。
sep: 我们使用的分隔符的类型。
collapse: 定义如何在字符串的矢量中以元素方式分隔结果。
连接两个字符串
# create 2 different strings.
string1 <- "Geeks" # first string
string2 <- "forGeeks" # second string.
# use cbind method to bind the strings into a vector.
vec <- cbind(string1, string2) # combined vector.
# use paste() function to perform string concatenation.
S <- paste(string1, string2, sep ="")
print(S)# print the output string
# collapse will determine how different
# elements are joined together.
M <- paste(vec, collapse = "#")
print(M) # print the output string using the collapse
输出
"GeeksforGeeks"
"Geeks#forGeeks"
使用不同类型的分隔符进行串联
在paste()函数的帮助下,我们可以通过使用不同类型的分隔符(如空格或一些特殊字符)进行连接。
# create 2 strings.
string1 <- "Hello" # first string
string2 <- "World" # second string
# concatenate by using whitespace as a separator.
S <- paste(string1, string2, sep =" ")
print(S)
M <- paste(string1, string2, sep =", ")
print(M)# concatenate by using ', ' character.
输出
Hello World
Hello, World
连接两个以上的字符串
在paste()函数的帮助下,我们可以将两个以上的字符串连接起来。
# create 3 different strings
string1 <- "I" # first string
string2 <- "Love" # second string
string3 <- "Programming" # third string.
# perform concatenation on multiple strings.
S <- paste(string1, string2, string3, sep =" ")
print(S) # print the output string.
输出
I Love Programming
cat()函数
同样,我们可以使用cat()函数进行连接,在该函数的帮助下,我们可以进行字符式连接,它还使我们可以灵活地将结果保存在一个文件中。
语法:
cat(string1, string2, …string, sep = “, file, append)
参数
string1, string2…string3: 为连接提供的字符串。
sep: 我们使用的分隔符类型。
file: 用于将结果保存在指定名称的文件中。
append: 逻辑参数,指定是否要将结果附加到现有文件中或创建一个新文件。
使用cat()函数串联两个或多个字符串。
我们可以通过插入字符串的变量名并指定分隔符来进行串联。我们还可以插入两个以上的变量并指定不同类型的参数。
# create 2 string variables
a <- 'Competitive'
b <- 'Coding'
c <- 'is difficult'
cat(a, b, c, sep = ' ')
输出
Competitive Coding is difficult
将连接的结果保存在一个文件中
为了保存串联输出的结果,我们可以在参数中指定文件的名称。默认情况下,append是假的,但是如果你想把结果追加到一个现有的文件中,那么指定append为TRUE。
,结果将被保存到指定的文件格式。
# create a list of 10 numbers and
# save it into file named temp.csv
cat(11:20, sep = '\n', file = 'temp.csv')
readLines('temp.csv') # read the file temp.csv
输出: