如何将字符串向量的最后一个字符大写?

问题描述 投票:-2回答:1

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

r regex stringr
1个回答
2
投票

基础R regex。

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)
© www.soinside.com 2019 - 2024. All rights reserved.