Reputation: 9985
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:
Upvotes: 6
Views: 1316
Reputation: 65867
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();
Upvotes: 2
Reputation: 5147
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?
Upvotes: 3