从R中字符删除换行符
在这篇文章中,我们将看到如何从一个R编程语言的删除新线。
例子:
Input: String with newline: "Hello\nGeeks\rFor\r\n Geeks"
Output: String after removing new line: "HelloGeeksFor Geeks"
方法一:使用 gsub()函数
R 语言中的gsub()函数用于替换字符串模式的所有匹配项。如果未找到模式,则字符串将按原样返回。
Syntax:
gsub(pattern, replacement, string, ignore.case=TRUE/FALSE)
Parameters:
pattern: string to be matched
replacement: string for replacement
string: String or String vector
ignore.case: Boolean value for case-sensitive replacement
实施例:R t程序使用GSUB()函数从中删除的换行符。
Syntax: gsub(“[\r\n]”, “”, string)
where
- [\r\n] is a first parameter which is a pattern to remove new lines
- “” is the second parameter that replaces when new line occurs as empty
- string is the input string of characters.
代码:
R
# consider a string
string = "Hello\nGeeks\nFor\nGeeks\n"
# display string
print("Original string: ")
cat(string)
# string after removing new lines
print("string after removing new lines: ")
cat(gsub("[\r\n]", "", string))
R
library(stringr)
# consider a string
string="Hello\nGeeks\rFor\r\nGeeks\n"
# display string
print("Original string: ")
cat(string)
# string after removing new lines
print("string after removing new lines: ")
print(str_replace_all(string, "[\r\n]" , ""))
输出:
[1] "Original string: "
Hello
Geeks
For
Geeks
[1] "string after removing new lines: "
HelloGeeksForGeeks
方法 2:使用 str_replace_all()函数
此函数可用在stringr包也被用于从删除新的线
Syntax: str_replace_all(string, “[\r\n]” , “”)
where
- string is the first parameter that takes string as input.
- [\r\n] is a second parameter which is a pattern to remove new lines
- “” is the third parameter that replaces when new line occurs as empty
示例:使用 stringr 包从字符串删除换行符的 R 程序
电阻
library(stringr)
# consider a string
string="Hello\nGeeks\rFor\r\nGeeks\n"
# display string
print("Original string: ")
cat(string)
# string after removing new lines
print("string after removing new lines: ")
print(str_replace_all(string, "[\r\n]" , ""))
输出:
[1] "Original string: "
Hello
Forks
Geeks
[1] "string after removing new lines: "
[1] "HelloGeeksForGeeks"