将两个单词的字符串中两个单词的首字母大写

编程入门 行业动态 更新时间:2024-10-25 05:22:48
本文介绍了将两个单词的字符串中两个单词的首字母大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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"

更多推荐

将两个单词的字符串中两个单词的首字母大写

本文发布于:2023-10-24 14:51:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524229.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单词   两个   字符串   首字母

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!