Count String Relpacements using Replace Function
-
Hi, I successfully use the string.replace function. Newstring = oldstring.replace(“*”,”~”) Now I want to count the number of replacements made. Thanks in advance! Kermit
Hi, String.Replace() or any other method wont tell you, but you could try a loop
int startPosition=0;
int n;
for (n=0; ;n++) {
startPosition=oldstring.IndexOf(searchString, startPosition)+1;
if (startPosition<=0) break;
}before performing the Replace. :)
Luc Pattyn
-
Hi, I successfully use the string.replace function. Newstring = oldstring.replace(“*”,”~”) Now I want to count the number of replacements made. Thanks in advance! Kermit
Perhaps it can be done using a RegEx replace and a delegate. That would give you the opportunity to do something for each replacement. A simple way (but not so effective if the string is large) is to create a string where you remove the character, and compare the lengths:
int cnt = oldstring.Length - oldstring.Replace("*", "").Length;
--- Year happy = new Year(2007);
-
Hi, I successfully use the string.replace function. Newstring = oldstring.replace(“*”,”~”) Now I want to count the number of replacements made. Thanks in advance! Kermit