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

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

问题描述

假设我有一个两个单词的字符串,我想大写两个.

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天全站免登陆