Splitting up a string, based on predicate
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:
- 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();
精彩评论