首页 > 解决方案 > 如何将字符串向量的最后一个字符大写?

问题描述

我刚开始使用 R,我想知道如何创建一个将字符串向量的最后一个字符大写的函数。

标签: rregexstringr

解决方案


基础 R 正则表达式:

words <- c("hello", "world")

# Last character of last word in vec element: 
gsub("(\\w$)", "\\U\\1", words, perl = TRUE)

sentences <- c("hello world", "hello friend")

# Last character of sentence: 
gsub("(\\w$)", "\\U\\1", sentences, perl = TRUE)

# Last character of each word in the sentence: 
gsub("(\\w\\s+|\\w$)", "\\U\\1", sentences, perl = TRUE)

推荐阅读