qwe2004
qwe2004

Reputation: 21

Split a string into two parts after the first word?

For example, I have a string

x <- 'what are you talking about'

How do I split it into two strings 'what' and 'are you talking about'?

Upvotes: 2

Views: 406

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174696

Do matching instead of splitting.

> x <- 'what are you talking about'
> library(stringi)
> stri_extract_all(x, regex="^\\S+|\\S.*")[[1]]
[1] "what"                          
[2] "are you talking about"

OR

> library(stringr)
> str_split(x, perl("^\\S+\\K\\s+"))
[[1]]
[1] "what"                          
[2] "are you talking about"

Upvotes: 1

thelatemail
thelatemail

Reputation: 93813

You can do it long hand, since strsplit won't play nice here:

val <- regexpr("\\s",x)
substring(x, c(1,val+1), c(val-1,nchar(x)) )
#[1] "what"                           "are you talking about"

Upvotes: 1

Related Questions