zesla
zesla

Reputation: 11813

capitalize the first letter of two words separated by underscore using stringr

I have a string like word_string. What I want is Word_String. If I use the function str_to_title from stringr, what I get is Word_string. It does not capitalize the second word.

Does anyone know any elegant way to achieve that with stringr? Thanks!

Upvotes: 1

Views: 1163

Answers (4)

NelsonGon
NelsonGon

Reputation: 13319

This is obviously overly complicating but another base possibility:

 test <- "word_string"
paste0(unlist(lapply(strsplit(test, "_"),function(x) 
  paste0(toupper(substring(x,1,1)),
           substring(x,2,nchar(x))))),collapse="_")
[1] "Word_String"

Upvotes: 2

akrun
akrun

Reputation: 887571

Can also use to_any_case from snakecase

library(snakecase)
to_any_case(str1, "title", sep_out = "_")
#[1] "Word_String"

data

str1 <- "word_string"

Upvotes: 3

yixi zhou
yixi zhou

Reputation: 297

You could first use gsub to replace "_" by " " and apply the str_to_title function

Then use gsub again to change it back to your format

x <- str_to_title(gsub("_"," ","word_string"))
gsub(" ","_",x)

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522161

Here is a base R option using sub:

input <- "word_string"
output <- gsub("(?<=^|_)([a-z])", "\\U\\1", input, perl=TRUE)
output

[1] "Word_String"

The regex pattern used matches and captures any lowercase letter [a-z] which is preceded by either the start of the string (i.e. it's the first letter) or an underscore. Then, we replace with the uppercase version of that single letter. Note that the \U modifier to change to uppercase is a Perl extension, so we must use sub in Perl mode.

Upvotes: 6

Related Questions