是否还有其他版本可以为每个字符串设置首字母,而且对于flac perl也是FALSE?
name<-"hallo"
gsub("(^[[:alpha:]])", "\\U\\1", name, perl=TRUE)
Run Code Online (Sandbox Code Playgroud)
alk*_*989 65
您可以尝试以下方式:
name<-"hallo"
paste(toupper(substr(name, 1, 1)), substr(name, 2, nchar(name)), sep="")
Run Code Online (Sandbox Code Playgroud)
或者另一种方法是拥有如下功能:
firstup <- function(x) {
substr(x, 1, 1) <- toupper(substr(x, 1, 1))
x
}
Run Code Online (Sandbox Code Playgroud)
例子:
firstup("abcd")
## [1] Abcd
firstup(c("hello", "world"))
## [1] "Hello" "World"
Run Code Online (Sandbox Code Playgroud)
Jac*_*sey 38
正如评论中指出的那样,现在可以做到:
stringr::str_to_title("iwejofwe asdFf FFFF")
stringr
使用stringi
这需要复杂的国际化,统一等保健引擎盖下,你可以这样做:
stri_trans_totitle("kaCk, DSJAIDO, Sasdd.", opts_brkiter = stri_opts_brkiter(type = "sentence"))
下面有一个C或C++库stringi
.
irJ*_*JvV 14
对于懒惰的人:
paste0(toupper(substr(name, 1, 1)), substr(name, 2, nchar(name)))
Run Code Online (Sandbox Code Playgroud)
也会这样做.
Oli*_*ver 13
在 中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"
Run Code Online (Sandbox Code Playgroud)
小智 10
我喜欢使用 stringr 和 oneliner 的“tidyverse”方式
library(stringr)
input <- c("this", "is", "a", "test")
str_replace(input, "^\\w{1}", toupper)
Run Code Online (Sandbox Code Playgroud)
导致:
[1] "This" "Is" "A" "Test"
Run Code Online (Sandbox Code Playgroud)
通常我们只需要第一个字母大写,其余的字符串小写。在这种情况下,我们需要先将整个字符串转换为小写。
受到@alko989 回答的启发,该功能将是:
firstup <- function(x) {
x <- tolower(x)
substr(x, 1, 1) <- toupper(substr(x, 1, 1))
x
}
Run Code Online (Sandbox Code Playgroud)
例子:
firstup("ABCD")
## [1] Abcd
Run Code Online (Sandbox Code Playgroud)
另一种选择是str_to_title
在stringr
包中使用
dog <- "The quick brown dog"
str_to_title(dog)
## [1] "The Quick Brown Dog"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
38153 次 |
最近记录: |