【问题标题】:First letter to upper case第一个字母大写
【发布时间】:2013-09-01 19:16:36
【问题描述】:

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

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

【问题讨论】:

  • 总是一个字吗?这可能会有所帮助 - How to convert a vector of strings to Title Case。查看@mnel 的回答
  • toupper 中的示例可能有用,例如.simpleCap
  • @Henrik 将每个单词都大写。
  • @zx8754 我看不到 perl flac FALSE 的解决方案
  • @SimonO101,也许我误解了克劳斯所说的“每个字符串”。

标签: r string


【解决方案1】:

你可以试试这样的:

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

或者另一种方式是有这样的功能:

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

例子:

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

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

【讨论】:

  • 这个我也注意到了,但是如果以后有变化的话,它看起来不太灵活
  • @Klaus 但它完全回答了您发布的问题。 有人发布有效答案后更改问题的参数是真的不好的形式。不酷/公平!问一个新问题。
  • 此外,有时还需要除第一个小写字符外的所有其他字符。因此,添加“x
【解决方案2】:

对于懒惰的打字员:

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

也会。

【讨论】:

  • 如果“超级懒惰”是指“知道paste0(x) 存在并且等价于paste(x, sep = '')”。
  • @KonradRudolph 你是 100% 正确的 -> 懒惰是指输入和维护的代码更少。 (如果您开始将代码连接到一个函数式编程行中会产生很大的不同——就像我经常做的那样——):^)
  • 而且 paste0 更快。
【解决方案3】:

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

stringr 在底层使用 stringi 来处理复杂的国际化、unicode 等,你可以这样做: stri_trans_totitle("kaCk, DSJAIDO, Sasdd.", opts_brkiter = stri_opts_brkiter(type = "sentence"))

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

【讨论】:

  • 现在有一个stringr wrapper:str_to_title
【解决方案4】:

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

受@alko989 答案的启发,函数将是:

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

例子:

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

另一种选择是在stringr 包中使用str_to_title

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

【讨论】:

    【解决方案5】:

    stringr 中,str_to_sentence() 做了类似的事情。这个问题的答案并不完全,但它解决了我遇到的问题。

    str_to_sentence(c("not today judas", "i love cats", "other Caps converteD to lower though"))
    #> [1] "Not today judas"  "I love cats"  "Other caps converted to lower though"  
    

    【讨论】:

    • 不明白为什么这被否决了。正是我想要的。赞成它。
    【解决方案6】:

    我喜欢将 stringr 与 oneliner 一起使用的“tidyverse”方式

    library(stringr)
    input <- c("this", "is", "a", "test")
    str_replace(input, "^\\w{1}", toupper)
    

    导致:

    [1] "This" "Is"   "A"    "Test"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-29
      • 1970-01-01
      相关资源
      最近更新 更多