通过索引快速替换字符串中的多个字符

编程入门 行业动态 更新时间:2024-10-28 12:17:35
本文介绍了通过索引快速替换字符串中的多个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试用另一个字符(例如*

I'm trying to quickly replace multiple characters in a string with another character such as *

例如,我有一个字符串,例如:

For example, I have a string such as:

string = "abcdefghij"

我还有一个索引向量,指示我要在上面的字符串中用另一个字符替换字母的位置.

I also have a vector of indexes that indicate where I would like to replace letters in the above string with another character.

string_indexes_replaced = c(1, 4, 6, 9)

所需的输出:

"*bc*e*gh*j"

我做了什么

我尝试了一种非常新手的方法,例如将字符分成列表,用*替换字符,然后将列表折叠回所需的字符串,如下所示:

I've tried a very novice like approach of splitting the characters up into a list, replacing the characters with *, then collapsing the list back into the desired string, as shown below:

library(dplyr) library(stringi) string%>% strsplit(split = "")%>% lapply(function(x) replace(x, string_indexes_replaced, rep("*", length(string_indexes_replaced))))%>% lapply(stri_flatten)%>% unlist(use.names = FALSE)

输出

"*bc*e*gh*j"

但是很明显,应该有比我上面发布的更简单,更快速的东西.有没有更简单的&比我在这里展示的要快?

but it is clear that there should be something simpler and faster than what I've posted above. Is there anything simpler & quicker than what I've demonstrated here?

推荐答案

,除了 @ akrun ,您可以使用utf8ToInt()和intToUtf8制作

in base R, besides the method of substring() and for-loop shown by @akrun,, you can use utf8ToInt() and intToUtf8 to make it

v <- utf8ToInt(string) v[string_indexes_replaced ] <- utf8ToInt("*") res <- intToUtf8(v)

给出

> res [1] "*bc*e*gh*j"

更多推荐

通过索引快速替换字符串中的多个字符

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

发布评论

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

>www.elefans.com

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