6

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

"ImageSizeTest" should become "Image Size Test"

Note: Uppercased character is the predicate

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.

Reference:

  1. Splitting a String with two criteria
Community
  • 1
  • 1
Maurits Rijk
  • 9,789
  • 2
  • 36
  • 53

2 Answers2

3

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
  • 5,107
  • 21
  • 27
  • 1
    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 Feb 15 '10 at 11:02
  • 2
    Added the part about the MatchEvaluator. Does that cover your needs for the predicate? – Paul Manzotti Feb 15 '10 at 11:08
  • 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 Feb 15 '10 at 11:38
  • 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 Feb 15 '10 at 11:53
  • 1
    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 Feb 15 '10 at 15:35
  • @MauritsRijk Can you publish your answer too? – LCJ Dec 21 '12 at 15:40
2
        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();
RameshVel
  • 64,778
  • 30
  • 169
  • 213