将两个单词的字符串中两个单词的首字母大写 [英] Capitalize the first letter of both words in a two word string

查看:229
本文介绍了将两个单词的字符串中两个单词的首字母大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有两个字词的字符串,我想大写 他们两个.

Let's say that I have a two word string and I want to capitalize both of them.

name <- c("zip code", "state", "final count")

Hmisc程序包具有函数capitalize,该函数将第一个单词大写,但我不确定 如何使第二个单词大写. capitalize的帮助页面并不建议它可以执行该任务.

The Hmisc package has a function capitalize which capitalized the first word, but I'm not sure how to get the second word capitalized. The help page for capitalize doesn't suggest that it can perform that task.

library(Hmisc)
capitalize(name)
# [1] "Zip code"    "State"       "Final count"

我想得到:

c("Zip Code", "State", "Final Count")

三个单词的字符串呢?

name2 <- c("I like pizza")

推荐答案

执行大写的基本R函数是toupper(x).在?toupper的帮助文件中,有此功能可以满足您的需求:

The base R function to perform capitalization is toupper(x). From the help file for ?toupper there is this function that does what you need:

simpleCap <- function(x) {
  s <- strsplit(x, " ")[[1]]
  paste(toupper(substring(s, 1,1)), substring(s, 2),
      sep="", collapse=" ")
}

name <- c("zip code", "state", "final count")

sapply(name, simpleCap)

     zip code         state   final count 
   "Zip Code"       "State" "Final Count" 

编辑:此功能适用于任何字符串,无论单词数如何:

Edit This works for any string, regardless of word count:

simpleCap("I like pizza a lot")
[1] "I Like Pizza A Lot"

这篇关于将两个单词的字符串中两个单词的首字母大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆