如何按位置替换部分字符串? [英] How to replace part of string by position?

查看:22
本文介绍了如何按位置替换部分字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个字符串:ABCDEFGHIJ

我需要用字符串 ZX

它看起来像这样:ABCZXFGHIJ

但不能与 string.replace("DE","ZX") 一起使用 - 我需要与 position

But not to use with string.replace("DE","ZX") - I need to use with position

我该怎么做?

推荐答案

在字符串中添加和删除范围的最简单方法是使用 StringBuilder.

The easiest way to add and remove ranges in a string is to use the StringBuilder.

var theString = "ABCDEFGHIJ";
var aStringBuilder = new StringBuilder(theString);
aStringBuilder.Remove(3, 2);
aStringBuilder.Insert(3, "ZX");
theString = aStringBuilder.ToString();

另一种方法是使用 String.Substring,但我认为 StringBuilder 代码变得更具可读性.

An alternative is to use String.Substring, but I think the StringBuilder code gets more readable.

这篇关于如何按位置替换部分字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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