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.
Asked
Active
Viewed 1,399 times
1

introiboad
- 997
- 1
- 11
- 18
2 Answers
4
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>

Colin Bacon
- 15,436
- 7
- 52
- 72
-
yep, this is perfect! Thanks very much indeed! – introiboad Oct 30 '12 at 18:37
1
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;

Pedro
- 12,032
- 4
- 32
- 45
-
I use the MSBuild Community tasks, so that would probably be better. How would one go about counting the items on that list? – introiboad Oct 30 '12 at 16:12