Bogaso
Bogaso

Reputation: 3308

Capitalise every word of a sentence except the very first letter

I want to capitalise every word of a sentence except the very first letter. There is a similar discussion here - Capitalize the first letter of both words in a two word string

So the function can be used as -

name <- c("zip code", "state", "final count")
simpleCap <- function(x) {
  s <- strsplit(x, " ")[[1]]
  paste(toupper(substring(s, 1,1)), substring(s, 2),
      sep="", collapse=" ")
}
sapply(name, simpleCap)

But it also capitalise the first letter as well. I want something like "zip Code" instead "Zip Code". Is there any way to achieve this?

Any help will be highly appreciated.

Upvotes: 2

Views: 70

Answers (3)

s_baldur
s_baldur

Reputation: 33488

With some basic regex:

name <- c("zip code", "state", "final count")
gsub("\\s([a-z])", " \\U\\1", name, perl = TRUE)
# [1] "zip Code"     "state"        "final Count"

To allow for non-ascii letters:

name <- c("zip code", "state", "final count", "uribe álvaro")
gsub("\\s(\\p{L})", " \\U\\1", name, perl = TRUE)
# [1] "zip Code"     "state"        "final Count"  "uribe Álvaro"

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388982

I like the second solution in that link using toTitleCase. You can use regex to make the first character lower-case.

simpleCap <- function(x) {
  sub('(.)', '\\L\\1', tools::toTitleCase(x), perl = TRUE)
}

simpleCap('Zip Code')
#[1] "zip Code"
simpleCap('this text')
#[1] "this Text"
simpleCap(name)
#[1] "zip Code"    "state"       "final Count"

Upvotes: 3

arg0naut91
arg0naut91

Reputation: 14764

Or with slight modification of the strsplit approach:

capExceptFirst <- function(x) {
  s <- strsplit(x, " ")[[1]]
  
  paste(
    tolower(s[1]),
    paste(toupper(substring(s[-1], 1,1)), substring(s[-1], 2),
        sep="", collapse=" "),
    collapse = " "
  )
}

sapply(name, capExceptFirst)

Output:

     zip code         state   final count 
   "zip Code"      "state " "final Count" 

Upvotes: 2

Related Questions