tags:

views:

65

answers:

2

I want to split up a string, based on a predicate. As an example:

"ImageSizeTest" should become "Image Size Test"

Of course I could write a simple loop, going through the string, check for uppercased characters (the predicate) and build the new string. However I want this to be a bit more general, splitting up based on any predicate. Still not very hard to implement, but I was wondering if there is an elegant way to do this using Linq.

+2  A: 

I take it that you don't want to split it into an array, but rather introduce spaces to a string? If so, you could use a regular expression to replace each upper case character with [space] character. You'd need to trim off the leading space though.

Sorry, to answer the full question, you could make it more generic by passing in the regular expression to match and the string to replace the matches with.

Looking at http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx, could you not consider the MatchEvaluator to be your predicate?

Paul Manzotti
I guess I should have explained myself a bit more clear: I want to be able to use any predicate function: 'bool MyPredicate(char c)'
Maurits Rijk
Added the part about the MatchEvaluator. Does that cover your needs for the predicate?
Paul Manzotti
The MatchEvaluator looks more like the action (for example insert a space) I want to execute. Nevertheless +1 since this is very useful.
Maurits Rijk
You could supply the Regex pattern as an argument, as well as the MatchEvaluator. Wouldn't that provide you with a general splitting method?
Paul Manzotti
Thanks! I decided on using a Regex.Replace in combination with the MatchEvaluator. Not a 100 % generic solution but good enough for the time being.
Maurits Rijk
+1  A: 
        string test ="ImageSizeTest";

        string pattern = "[A-Z]";
        Regex AllCaps = new Regex(pattern);                       

        var fs = test.ToCharArray().Select(x =>
        {
            if (AllCaps.IsMatch(x.ToString()))
                return " " + x.ToString();

            return x.ToString();
        }).ToArray();

        var resss =string.Join("",fs).Trim();
Ramesh Vel