如何在R中的多行字符串中查找字符串第一行的长度

How to find the length of the first line of a string in a multi line string in R

我正在研究 R 中的以下问题

[注意:我发现有一个类似问题的答案是

但是 我正在寻找 R 中的解决方案,而不是 python。 ]

假设我有一个多行字符串,如下所示:

"The first line of the string,
the second line of the string
and finally the the third line of the string."

我想知道字符串第一行的长度是:

> nchar("The first line of the string,")
[1] 29

然而字符串实际上存储为

> "The first line of the string,
+ the second line of the string
+ and finally the the third line of the string"
[1] "The first line of the string,\nthe second line of the string\nand finally the the third line of the string"

所以当我将 nchar 函数应用于整个字符串时,我得到

> my_string = "The first line of the string,
+ the second line of the string
+ and finally the the third line of the string"
> nchar(my_string)
[1] 104

这是不正确的。

有什么方法可以只获取第一行的字符数吗?

我找到了一个解决方案:

nchar(strsplit(my_string, "\n")[[1]])

也许存在更好的。

baseR 解决方案

nchar( gsub( "(^[^\n]*).*$", "\1", my_string) )

从字符串的开头开始,直到第一个 \n (=换行符)

您可以使用 sub 删除 \n 之后的所有内容,然后使用 nchar.

nchar(sub("\n.*", "", my_string))
#[1] 29

或使用strsplit

nchar(strsplit(my_string, "\n")[[1]][1])
#nchar(strsplit(my_string, "\n")[[c(1,1)]]) #Alternative
#[1] 29