如何在C#中替换字符串的一部分? [英] How do I replace part of a string in C#?
本文介绍了如何在C#中替换字符串的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下字符串:
string str = "<tag>text</tag>";
我想将'tag'更改为'newTag',结果将是:
And I would like to change 'tag' to 'newTag' so the result would be:
"<newTag>text</newTag>"
最好的方法是什么?
我尝试搜索< [/] * tag>,但是随后我不知道如何在结果中保留可选的[/]...
I tried to search for <[/]*tag> but then I don't know how to keep the optional [/] in my result...
推荐答案
为什么可以使用正则表达式:
Why use regex when you can do:
string newstr = str.Replace("tag", "newtag");
或
string newstr = str.Replace("<tag>","<newtag>").Replace("</tag>","</newtag>");
编辑为@RaYell的评论
Edited to @RaYell's comment
这篇关于如何在C#中替换字符串的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文