R:如何替换字符串中的第 5 个元素? [英] R: How can I replace let's say the 5th element within a string?

查看:38
本文介绍了R:如何替换字符串中的第 5 个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将像 be33szfuhm100060 这样的字符串转换为 BESZFUHM0060.

I would like to convert the a string like be33szfuhm100060 into BESZFUHM0060.

为了用大写字母替换小写字母,我到目前为止使用了 gsub 函数.

In order to replace the small letters with capital letters I've so far used the gsub function.

test1=gsub("be","BE",test)

有没有办法告诉这个函数替换第 3 个和第 4 个字符串元素?如果没有,如果您能告诉我解决此问题的另一种方法,我将不胜感激.也许还有更通用的解决方案,可以将某个位置的字符串元素更改为大写字母,无论该元素是什么?

Is there a way to tell this function to replace the 3rd and 4th string element? If not, I would really appreciate if you could tell me another way to solve this problem. Maybe there is also a more general solution to change a string element at a certain position into a capital letter whatever the element is?

推荐答案

几点意见:

将字符串转换为大写可以使用 toupper 完成,例如:

Cnverting a string to uppercase can be done with toupper, e.g.:

> toupper('be33szfuhm100060')
> [1] "BE33SZFUHM100060"

您可以使用 substr 按字符位置提取子字符串并使用 paste 连接字符串:

You could use substr to extract a substring by character positions and paste to concatenate strings:

> x <- 'be33szfuhm100060'
> paste(substr(x, 1, 2), substr(x, 5, nchar(x)), sep='')
[1] "beszfuhm100060"

这篇关于R:如何替换字符串中的第 5 个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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