views:

3212

answers:

4

Using VB.Net I'd like to be able to replace a range of characters in a string in a single line of code.

i.e. something like

Dim charsToReplace as string = "acegi"
Dim stringToBeReplaced as string = "abcdefghijklmnop"

charsToReplace.ToArray().ForEach(Function (c) stringTobeReplaced = stringTobeReplaced.Replace(c, ""))

however, this doesn't work.

the following does work, however I don't want the string to be a class level variable:

 Sub Main()
    Dim toReplace As String = "acegikmoq"


    Console.WriteLine(mainString)
    Dim chars As List(Of Char) = toReplace.ToList()
    chars.ForEach(AddressOf replaceVal)

    Console.WriteLine(mainString)
    Console.ReadLine()

End Sub

Dim mainString As String = "this is my string that has values in it that I am going to quickly replace all of..."

Sub replaceVal(ByVal c As Char)
    mainString = mainString.Replace(c, "")
End Sub

Can this be done?

A: 

String class has replace method to do this. You can use it this way:

YourString = YourString.Replace("OldValue","NewValue")
danish
I may not have been completely clear, but I want to replace every instance of every character in the string. i.e. chars = "ace"longString = "abcdeabcdeabcde"result = "bdbdbd"replace is not able to do this.
hitch
+4  A: 

If I read this correctly, you're trying to strip a list of characters from a string. This is a good fit for a RegEx.

Console.WriteLine(Regex.Replace("abcdefghijklmnop", "[acegi]", string.Empty))

(you'll need to import System.Text.RegularExpressions)

Jon Galloway
A: 

I recommend Jon Galloway's approach, a regular expression is the appropriate method, and future developers will thank you for it :) - though it's not a difficult problem to solve with Linq as well. Here's some (untested) C# code to do that:

string stringToBeReplaced = "abcdefghijklmnop";
string charsToReplace = "acegi";
stringToBeReplaced = new String(stringToBeReplaced.Where(c => !charsToReplace.Any(rc => c == rc)).ToArray());

I suspect this code will probably perform slightly better then the regex equivalent, if performance is an issue.

Bittercoder
+2  A: 

The RegEx approach is the best suited, but what I really need to say is:

Please, for the love of maintenance developers, don't get hung-up on getting this down to 1 line of code. One method call is your real goal, if you end up just piling a bunch of calls into 1 line to say it's one-line then you're shooting yourself in the foot.

STW
It's not really my main goal to get it to one line for development purposes, more for "got a bee in my bonnet because it didn't work how I thought it should, and want to figure out how to do it" purposes... :)
hitch
+1 for the maintenance developers - been there, done that, had that headache! =)
Rob