I have a string "JohnMarkMarkMark"
I want to replace the "Mark" with "Tom" with two cases
In first case i want to replace only first occurance of "Mark" Result will be: "JohnTomMarkMark" In the second case i want to replace all the occuran开发者_开发技巧ce of "Mark" Result will be: "JohnTomTomTom"
Please suggest Thnaks
string data = "JohnMarkMarkMark";
string resultOne = new Regex("Mark").Replace(data, "Tom", 1);
string resultAll = data.Replace("Mark", "Tom");
For the first case, use IndexOf, Substring and Concat.
For the second case, use Replace.
(1) is:
var inString = "TestMarkMarkMark";
var lookFor = "Mark";
var replaceWith = "Tom";
var length = lookFor.Length;
var first = inString.IndexOf(lookFor);
var newString = inString.Substring(0, first) + replaceWith + inString.Substring(first + length);
Which could be optimized, but I've expanded it out so it's easy to follow.
(2) is trivial - just do inString.Replace("Mark", "Tom");
for case 1 try this
string s = "JohnMarkMarkMark";
Regex x = new Regex("Mark");
MatchCollection m = x.Matches(s);
if (m!=null && m.Count > 0)
{
s = s.Remove(m[0].Index, m[0].Length);
s = s.Insert(m[0].Index,"Tom");
}
for case 2 try s = s.Replace("Mark","Tom");
精彩评论