どうも、ちょげ(@chogetarou)です。
文字列(string)の先頭文字を大文字に変換する方法を紹介します。
方法

文字列(string)の先頭文字を大文字に変換する方法は、4つあります。
gsub()
1つ目は、gsub()を使う方法です。
まず、gsub()を呼び出します。
gsub()の第1引数に「"(^|[[:space:]])([[:alpha:]])"
」、第2引数に「"\\1\\U\\2"
」を指定します。
そして、gsub()の第3引数に対象の文字列、第4引数「perl」に「TRUE」を指定します。
#text=対象の文字列
result <- gsub("(^|[[:space:]])([[:alpha:]])", "\\1\\U\\2", text, perl=TRUE)
上記のgsub()は、対象の文字列(string)の先頭文字を大文字に変換した結果を返します。
使用例
text <- "hello"
result <- gsub("(^|[[:space:]])([[:alpha:]])", "\\1\\U\\2", text, perl=TRUE)
print(result)
出力:
> print(result)
[1] "Hello"
tools
2つ目は、toolsを使う方法です。
まず、toolsを導入します。
library(tools)
次に、toTitleCase()を呼び出します。
そして、toTitleCase()の引数に文字列を指定します。
#text=対象の文字列
result <- toTitleCase(text)
上記のtoTitleCase()は、対象の文字列(string)の先頭文字を大文字に変換した結果を返します。
使用例
library(tools)
text <- "hello"
result <- toTitleCase(text)
print(result)
出力:
> print(result)
[1] "Hello"
stringi
3つ目は、stringiを使う方法です。
まず、stringiを導入します。
library(stringi)
次に、stri_trans_totitle()を呼び出します。
そして、stri_trans_totitle()の引数に文字列を指定します。
#text=対象の文字列
result <- stri_trans_totitle(text)
上記のstri_trans_totitle()は、対象の文字列(string)の先頭文字を大文字に変換した結果を返します。
使用例
library(stringi)
text <- "hello"
result <- stri_trans_totitle(text)
print(result)
出力:
> print(result)
[1] "Hello"
stringr
4つ目は、stringrを使う方法です。
まず、stringrを導入します。
library(stringr)
次に、str_to_title()を呼び出します。
そして、str_to_title()の引数に文字列を指定します。
#text=対象の文字列
result <- str_to_title(text)
上記のstr_to_title()は、対象の文字列(string)の先頭文字を大文字に変換した結果を返します。
使用例
library(stringr)
text <- "hello"
result <- str_to_title(text)
print(result)
出力:
> print(result)
[1] "Hello"
まとめ
文字列(string)の先頭文字を大文字に変換する方法は、次の4つです。
- gsub()を使う方法
result <- gsub("(^|[[:space:]])([[:alpha:]])", "\\1\\U\\2", text, perl=TRUE)
- toolsを使う方法
result <- toTitleCase(text)
- stringiを使う方法
result <- stri_trans_totitle(text)
- stringrを使う方法
result <- str_to_title(text)
コメント