Home > OS >  How to change the words in a sentence (string) to Title Case, where the conjunctions in the sentence
How to change the words in a sentence (string) to Title Case, where the conjunctions in the sentence

Time:04-21

I need to know how to change the words in a sentence (string) to Title Case, where the conjunctions in the sentence have to stay or change to lower letters (all the word).

Something similar to str_to_title(sentence, locale = "en"), from the string library, but in which the function recognizes conjunctions (for, and, the, from, etc.). The most common coordinating conjunctions are: for, and, nor, but, or, yet, and so.

Also, it is important that the word the stay as lower case but not when is the first word. The first and last words should always have the first letter in upper case.

For example:

sentence = "THE LOVer Tells OF THE rose in HIS HEART"

I want the string sentence to change to:

"The Lover Tells of the Rose in His Heart" 

Which is called a Title Case.

Any help is appreciated

CodePudding user response:

How about this solution? I figured your question out of programming.

sentence <- "THE LOVer Tells OF THE rose in HIS HEART"

require(stringr)

words <- unlist(strsplit(sentence,' ')) %>% tolower()
conjunctions <- c('for', 'and', 'nor', 'but', 'or', 'yet','the','of','in')
for(i in seq_len(length(words))){
  if(i==1 & words[i] %in% conjunctions){
    words[i] <- str_to_title(words[i])
  } else if (!words[i] %in% conjunctions) {
    words[i] <- str_to_title(words[i])
  }
}
words
result <- paste(words, collapse=' ')
result
  1. Split a sentence to words and and make them tolower.
  2. Coordinating conjunctions ,except the first word, would be passed and other words would str_to_title.
  3. paste the words into a sentence.

The result would be [1] "The Lover Tells of the Rose in His Heart"

  • Related