Is there a fast way (without having to explicitly looping through each character in a string) and either stripping or keeping it. In Visual FoxPro, there is a function CHRTRAN() that does it great. Its on a 1:1 character replacement, but if no character in the alternate position, its stripped from the final string. Ex
CHRTRAN( "This will be a test", "it", "X" )
will return
"ThXs wXll be a es"
Notice the original "i" is converted to "X", and lower case "t" is stripped out.
I looked at the replace for similar intent, but did not see an option to replace with nothing.
I'm looking to make some generic routines to validate multiple origins of data that have different types of input restrictions. Some of the data may be coming from external sources, so its not just textbox entry validation I need to test for.
Thanks
This is a case where I think using LINQ overcomplicates the matter. This is simple and to the point:
All you need is a couple of calls to String.Replace().
Note that Replace() returns a new string. It does not alter the string itself.
A more general version as a string extension. Like the others this does not do a translation in place since strings are immutable in C#, but instead returns a new string with the replacements as specified.
Here was my final function and works perfectly as expected.
Does this what you want?
Here is a simple implementation of the
CHRTRAN
function - it does not work if the string contains\0
and is quite messy. You could write a nicer one using loops, but I just wanted to try it using LINQ.And the you can use it.
Just to have a clean solution - the same without LINQ and working for the
\0
cases, too, and it is almost in place because of using aStringBuilder
but won't modify the input, of course.Null reference handling is missing.
Inspired by tvanfosson's solution, I gave LINQ a second shot.
To "replace with nothing", just replace with an empty string. This will give you: