string 将两个单词字符串中两个单词的首字母大写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6364783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:08:49  来源:igfitidea点击:

Capitalize the first letter of both words in a two word string

rstringtitle-case

提问by ATMathew

Let's say that I have a two word string and I want to capitalize both of them.

假设我有一个两个单词的字符串,我想将它们都大写。

name <- c("zip code", "state", "final count")

The Hmiscpackage has a function capitalizewhich capitalized the first word, but I'm not sure how to get the second word capitalized. The help page for capitalizedoesn't suggest that it can perform that task.

Hmisc包具有capitalize将第一个单词大写的功能,但我不确定如何将第二个单词大写。的帮助页面capitalize并不表明它可以执行该任务。

library(Hmisc)
capitalize(name)
# [1] "Zip code"    "State"       "Final count"

I want to get:

我想得到:

c("Zip Code", "State", "Final Count")

What about three-word strings:

三字串呢:

name2 <- c("I like pizza")

采纳答案by Andrie

The base R function to perform capitalization is toupper(x). From the help file for ?toupperthere is this function that does what you need:

执行大写的基本 R 函数是toupper(x)。从帮助文件中?toupper有此功能可以满足您的需求:

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

name <- c("zip code", "state", "final count")

sapply(name, simpleCap)

     zip code         state   final count 
   "Zip Code"       "State" "Final Count" 

EditThis works for any string, regardless of word count:

编辑这适用于任何字符串,无论字数如何:

simpleCap("I like pizza a lot")
[1] "I Like Pizza A Lot"

回答by petermeissner

There is a build-in base-R solutionfor title case as well:

标题案例也有一个内置的base-R 解决方案

tools::toTitleCase("demonstrating the title case")
## [1] "Demonstrating the Title Case"

or

或者

library(tools)
toTitleCase("demonstrating the title case")
## [1] "Demonstrating the Title Case"

回答by Martin Morgan

Match a regular expression that starts at the beginning ^or after a space [[:space:]]and is followed by an alphabetical character [[:alpha:]]. Globally (the g in gsub) replace all such occurrences with the matched beginning or space and the upper-case version of the matched alphabetical character, \\1\\U\\2. This has to be done with perl-style regular expression matching.

匹配以^空格开头或[[:space:]]后跟字母字符的正则表达式[[:alpha:]]。全局(gsub 中的 g)用匹配的开头或空格以及匹配的字母字符的大写版本替换所有此类出现\\1\\U\\2。这必须通过 perl 风格的正则表达式匹配来完成。

gsub("(^|[[:space:]])([[:alpha:]])", "\1\U\2", name, perl=TRUE)
# [1] "Zip Code"    "State"       "Final Count"

In a little more detail for the replacement argument to gsub(), \\1says 'use the part of xmatching the first sub-expression', i.e., the part of xmatching (^|[[:spacde:]]). Likewise, \\2says use the part of xmatching the second sub-expression ([[:alpha:]]). The \\Uis syntax enabled by using perl=TRUE, and means to make the next character Upper-case. So for "Zip code", \\1is "Zip", \\2is "code", \\U\\2is "Code", and \\1\\U\\2is "Zip Code".

在替换参数的更多细节中gsub()\\1说“使用x匹配第一个子表达式的部分”,即x匹配的部分(^|[[:spacde:]])。同样,\\2表示使用x匹配第二个子表达式的部分([[:alpha:]])。的\\U是使用支持语法perl=TRUE和手段,使下一个字符大写。所以对于“邮政编码”,\\1是“邮政编码”,\\2是“代码”,\\U\\2是“代码”,\\1\\U\\2是“邮政编码”。

The ?regexppage is helpful for understanding regular expressions, ?gsubfor putting things together.

?regexp页面有助于理解正则表达式,?gsub将事物组合在一起。

回答by bartektartanus

Use this function from stringipackage

stringi包中使用此功能

stri_trans_totitle(c("zip code", "state", "final count"))
## [1] "Zip Code"      "State"       "Final Count" 

stri_trans_totitle("i like pizza very much")
## [1] "I Like Pizza Very Much"

回答by Brijesh

Alternative:

选择:

library(stringr)
a = c("capitalise this", "and this")
a
[1] "capitalise this" "and this"       
str_to_title(a)
[1] "Capitalise This" "And This"   

回答by diliop

Try:

尝试:

require(Hmisc)
sapply(name, function(x) {
  paste(sapply(strsplit(x, ' '), capitalize), collapse=' ')
})

回答by Chase

From the help page for ?toupper:

从帮助页面?toupper

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


> sapply(name, .simpleCap)

zip code         state   final count 
"Zip Code"       "State" "Final Count"

回答by Dirk

The package BBmiscnow contains the function capitalizeStrings.

该包BBmisc现在包含函数capitalizeStrings

library("BBmisc")
capitalizeStrings(c("the taIl", "wags The dOg", "That Looks fuNny!")
    , all.words = TRUE, lower.back = TRUE)
[1] "The Tail"          "Wags The Dog"      "That Looks Funny!"

回答by greg L

Alternative way with substring and regexpr:

子字符串和正则表达式的替代方法:

substring(name, 1) <- toupper(substring(name, 1, 1))
pos <- regexpr(" ", name, perl=TRUE) + 1
substring(name, pos) <- toupper(substring(name, pos, pos))

回答by Taz

You could also use the snakecase package:

你也可以使用snakecase包:

install.packages("snakecase")
library(snakecase)

name <- c("zip code", "state", "final count")
to_title_case(name)
#> [1] "Zip Code"    "State"       "Final Count"

# or 
to_upper_camel_case(name, sep_out = " ")
#> [1] "Zip Code"    "State"       "Final Count"

https://github.com/Tazinho/snakecase

https://github.com/Tazinho/snakecase