user10367073
user10367073

Reputation:

Splitting the sentence that has 2 similar words

I need to split the words in a sentence but have some issues here

word.list1 <- c("rose","location","criminal","lotus","check","sing","single")

if you look at above code, sing and single are 2 words that I have in my list

Now i have a sentence

a <- "rosesinglelocationcriminalcheck"

Following code will split the words

for (word in word.list) {
  a <- gsub(word, paste0(word, " "), a)     }

> a1

[1] "rose sing le location criminal check "

Actually I need the output like below

> a1

[1] "rose single location criminal check "

Since my I have both sing and single in my list. The code is taking sing actually. Is there anywhere to split the words

Upvotes: 6

Views: 85

Answers (1)

Birger
Birger

Reputation: 1141

For that special case just switch whitespace in gsub:

word.list <- c("rose","location","criminal","lotus","check","sing","single")

a <- "rosesinglelocationcriminalcheck"
for (word in word.list) {
  a <- gsub(word, paste0(" ", word), a)     
}
a
#> [1] " rose  single location criminal check"

However I guess that approach is very limited. What about singlet? sing, let and singlet are all meaningful words.

Upvotes: 1

Related Questions