string 大写的第一个字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18509527/
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 02:04:24  来源:igfitidea点击:

First letter to upper case

rstring

提问by Klaus

Is there a other version to make the first letter of each string capital and also with FALSE for flac perl?

是否有其他版本可以使每个字符串的第一个字母大写,并且对于 flac perl 还使用 FALSE?

name<-"hallo"
gsub("(^[[:alpha:]])", "\U\1", name, perl=TRUE)

回答by alko989

You can try something like:

您可以尝试以下操作:

name<-"hallo"
paste(toupper(substr(name, 1, 1)), substr(name, 2, nchar(name)), sep="")

Or another way is to have a function like:

或者另一种方法是具有如下功能:

firstup <- function(x) {
  substr(x, 1, 1) <- toupper(substr(x, 1, 1))
  x
}

Examples:

例子:

firstup("abcd")
## [1] Abcd

firstup(c("hello", "world"))
## [1] "Hello" "World"

回答by Hyman Wasey

As pointed out in the comment, it is now possible to do: stringr::str_to_title("iwejofwe asdFf FFFF")

正如评论中所指出的,现在可以这样做: stringr::str_to_title("iwejofwe asdFf FFFF")

stringruses stringiunder the hood which takes care of complex internationalization, unicode, etc., you can do: stri_trans_totitle("kaCk, DSJAIDO, Sasdd.", opts_brkiter = stri_opts_brkiter(type = "sentence"))

stringrstringi在处理复杂国际化、unicode 等的引擎盖下使用,您可以执行以下操作: stri_trans_totitle("kaCk, DSJAIDO, Sasdd.", opts_brkiter = stri_opts_brkiter(type = "sentence"))

There is a C or C++ library underneath stringi.

下面有一个 C 或 C++ 库stringi

回答by irJvV

for the lazy typer:

对于懒惰的打字机:

  paste0(toupper(substr(name, 1, 1)), substr(name, 2, nchar(name)))

will do too.

也会做。

回答by laviex

Often we want onlythe first letter upper case, rest of the string lower case. In such scenario, we need to convert the whole string to lower case first.

通常我们需要第一个字母大写,其余的字符串小写。在这种情况下,我们需要先将整个字符串转换为小写。

Inspired by @alko989 answer, the function will be:

受到@alko989 回答的启发,该功能将是:

firstup <- function(x) {
  x <- tolower(x)
  substr(x, 1, 1) <- toupper(substr(x, 1, 1))
  x
}

Examples:

例子:

firstup("ABCD")
## [1] Abcd

Another option is to use str_to_titlein stringrpackage

另一种选择是str_to_titlestringr包中使用

dog <- "The quick brown dog"    
str_to_title(dog)
## [1] "The Quick Brown Dog"