R中的空格分割字符
在这篇文章中,我们将讨论如何在R编写空格分开的字符串。
方法一:使用strsplit()函数
strsplit()函数用于根据某些条件拆分字符串。
句法:
strsplit(input_string, ” +”)
在哪里
- input_string 是字符串
- “+”代表在空白处分割
示例:用于拆分给定字符串的R 程序
R
# consider a string with white spaces
string1="Hello Geeks we are in Java Python R and CPP"
# split the string by using strsplit() function
print(strsplit(string1, " +"))
R
# consider a string with white spaces
string1="Hello Geeks we are in Java Python R and CPP"
# split the string by using strsplit() function
print(strsplit(string1, " +")[[1]])
R
# consider a string with white spaces
string1="Hello Geeks we are in Java Python R and CPP"
# split the string by using scan() function
print(scan(text = string1, what = ""))
R
# consider a string with white spaces
string1="There are big branches in India"
# split the string by using scan() function
print(scan(text = string1, what = ""))
输出:
[[1]]
[1] “Hello” “Geeks” “we” “are” “in” “Java” “Python” “R”
[9] “and” “CPP”
它存储在列表中的索引 1 中,因此我们可以使用索引 1 位置稍微修改我们的代码。
示例:用于拆分给定字符串的R 程序
电阻
# consider a string with white spaces
string1="Hello Geeks we are in Java Python R and CPP"
# split the string by using strsplit() function
print(strsplit(string1, " +")[[1]])
输出:
[1] “Hello” “Geeks” “we” “are” “in” “Java” “Python” “R”
[9] “and” “CPP”
方法二:使用scan()函数
该函数还用于通过扫描元素来拆分字符串。
句法:
scan(text = input_string, what = “”)
在哪里,
- text 参数用于存储输入字符串
- 什么是可以带空格的参数,它指定要在空格处拆分的字符串
它还将显示扫描了多少次(它将返回拆分单词的数量)。
示例:使用 scan()函数在空白处拆分字符串的R 程序
电阻
# consider a string with white spaces
string1="Hello Geeks we are in Java Python R and CPP"
# split the string by using scan() function
print(scan(text = string1, what = ""))
输出:
Read 10 items
[1] “Hello” “Geeks” “we” “are” “in” “Java” “Python” “R”
[9] “and” “CPP”
示例:使用 scan()函数在空白处拆分字符串的R 程序
电阻
# consider a string with white spaces
string1="There are big branches in India"
# split the string by using scan() function
print(scan(text = string1, what = ""))
输出:
Read 6 items
[1] “There” “are” “big” “branches” “in” “India”