Count character ocurrences in a string in MSBuild
-
21-07-2021 - |
Question
What's the easiest way to count the number of times a character ('\' in my case) appears in a string using MSBuild? I tried using Split(\
) to no avail.
Solution
MsBuild 4.0 allows the use of property functions http://msdn.microsoft.com/en-us/library/dd633440.aspx
You can use this to split the string. You must then substract the length by 1 to get the occurrence count.
<Target Name="SplitCount">
<PropertyGroup>
<path>test\document\home</path>
</PropertyGroup>
<PropertyGroup>
<test>$(path.Split('\').length)</test>
</PropertyGroup>
<Message Text="occurrence count: $([MSBuild]::Subtract($(test), 1))"><Message>
</Target>
OTHER TIPS
In the MSBuild Community Tasks, there is a RegexMatch task that would give you a list, which you could then count perhaps.
Another option would be to write your own custom task. Then add a bit of Linq like so:
string input = "This \\ is \\ a \\ test";
var items = (from c in input where c == '\\' select c).ToList();
var count = items.Count;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow