替换字符串中第一次出现的模式 [英] Replace first occurrence of pattern in a string
本文介绍了替换字符串中第一次出现的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
如何替换.NET 中字符串的第一个实例?
假设我有字符串:
string s = "Hello world.";
如何替换 Hello
单词中的第一个 o
比如说 Foo
?
how can I replace the first o
in the word Hello
for let's say Foo
?
换句话说,我想以:
"HellFoo world."
我知道如何替换所有的 o 但我只想替换第一个
I know how to replace all the o's but I want to replace just the first one
推荐答案
我认为你可以使用 Regex.Replace 指定最大替换次数...
I think you can use the overload of Regex.Replace to specify the maximum number of times to replace...
var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);
这篇关于替换字符串中第一次出现的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文