[英]First letter to upper case
是否有其他版本可以使每個字符串的第一個字母大寫,並且對於 flac perl 也使用 FALSE?
name<-"hallo"
gsub("(^[[:alpha:]])", "\\U\\1", name, perl=TRUE)
您可以嘗試以下操作:
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"
正如評論中指出的,現在可以這樣做: stringr::str_to_title("iwejofwe asdFf FFFF")
stringr
在stringr
使用stringi
來處理復雜的國際化、unicode 等,你可以這樣做: stri_trans_totitle("kaCk, DSJAIDO, Sasdd.", opts_brkiter = stri_opts_brkiter(type = "sentence"))
stringi
下面有一個 C 或 C++ 庫。
對於懶惰的打字機:
paste0(toupper(substr(name, 1, 1)), substr(name, 2, nchar(name)))
也會做。
在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"
通常我們只需要第一個字母大寫,其余的字符串小寫。 在這種情況下,我們需要先將整個字符串轉換為小寫。
受到@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"
我喜歡使用 stringr 和 oneliner 的“tidyverse”方式
library(stringr)
input <- c("this", "is", "a", "test")
str_replace(input, "^\\w{1}", toupper)
導致:
[1] "This" "Is" "A" "Test"
我也在尋找這個問題的答案,但回復沒有考慮以數字或符號開頭的字符串的情況。 另外,問題是:“使每個字符串的第一個字母大寫”,而不是每個單詞。
v = c("123.1 test test", "test", "test test", ". test")
stringr::str_replace(v, "([[:alpha:]])", toupper)
## [1] "123.1 Test test" "Test" "Test test" ". Test"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.