|
-
Oct 4th, 2007, 02:07 PM
#1
Thread Starter
Fanatic Member
Count replaces in Stringbuilder
Hello,
Just curious if this can be done. Is there a way to count the number of replaces or finds in a stringbuilder?
Note: I want to avoid having to loop through the file to count them prior to performing the replace. This'll probably be the route I go if it can't be done in Stringbuilder. I'm using VB 2005.
Thanks in advance,
Strick
-
Oct 4th, 2007, 06:10 PM
#2
Re: Count replaces in Stringbuilder
vb Code:
Dim sb As New System.Text.StringBuilder("Hi I am Some data I am!")
Dim replaceArg As String = "I"
Dim replacements As Integer = (sb.Length - sb.Replace(replaceArg, "").Length) / replaceArg.Length
-
Oct 4th, 2007, 06:18 PM
#3
Re: Count replaces in Stringbuilder
Bill that looks like it would only work if you were replacing single characters. What about if you were to replace a 4 letter word with "". Your result would be 4, when the actual number of replacements is actually 1.
I guess not enough specs were provided by the thread starter to give an accurate answer though.
-
Oct 4th, 2007, 06:52 PM
#4
Re: Count replaces in Stringbuilder
(sb.Length - sb.Replace(replaceArg, "").Length) = 4
replaceArg.Length = 4
4 /4 = 1
-
Oct 4th, 2007, 07:01 PM
#5
Re: Count replaces in Stringbuilder
 Originally Posted by wild_bill
vb Code:
Dim sb As New System.Text.StringBuilder("Hi I am Some data I am!")
Dim replaceArg As String = "I"
Dim replacements As Integer = (sb.Length - sb.Replace(replaceArg, "").Length) / replaceArg.Length
That's all very well if you're removing substrings by replacing them with an empty string. What if you're replacing substrings with another substring of equal length? The original and the final will both have the same length so your result would be zero regardless.
-
Oct 4th, 2007, 07:04 PM
#6
Re: Count replaces in Stringbuilder
True, but I thought he just wanted a count. Another option would be to write a simple regex.
-
Oct 4th, 2007, 07:21 PM
#7
Thread Starter
Fanatic Member
Re: Count replaces in Stringbuilder
Hi, I'm looking to count the number of replace(s) done. This can be a word or single character. So,
Dim sb As New System.Text.StringBuilder("This is test1. This is test2")
So if i replace "This" with "That" the count would be 2 and both "this" would get replaced with "that"
Thanks,
Strick
-
Oct 4th, 2007, 07:36 PM
#8
Re: Count replaces in Stringbuilder
The StringBuilder doesn't provide that functionality, plain and simple. If it did then it would be documented in the Help for the Replace method. It is up to you to count the number of substrings that will be replaced before you replace them. Wild_bill's last suggestion of using a Regex would be the best way of doing that.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|