开发者

Splitting up a string, based on predicate

开发者 https://www.devze.com 2022-12-20 00:30 出处:网络
I want to split up a stri开发者_JS百科ng, based on a predicate. As an example: \"ImageSizeTest\" should become \"Image Size Test\"

I want to split up a stri开发者_JS百科ng, 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


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?


        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();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号