Search code examples
rstringtm

Count the number of words without white spaces


I have the following string:

str1<-" india hit milestone electricity wind solar"

Number of words contained in it is:

>sapply(strsplit(str1, " "), length)
[1] 7

It is not true because we have a space at the beginning of str1. I tried to trim the white space but:

> stripWhitespace(str1) # by tm package

returns the same situation:

[1] " india hit milestone electricity wind solar"

Why?


Solution

  • You can just use the base function trimws

    sapply(strsplit(trimws(str1), " "), length)
    [1] 6