Reputation: 1
I have a string like below and I want to know the depth
Assb/vvv/jjj
Sss/jjk/gyii/fff
The 1st will give me 3 level and 2nd one will give me 4 level.
How to code and count number of backslash in tcl?
Upvotes: 0
Views: 77
Reputation: 137567
There are a few ways. Here are two that count slightly different things:
Count the /
characters with regexp -all
, helped by the fact that /
is not an RE metacharacter:
# Always put REs in braces… but in this case it doesn't matter much
set count [regexp -all {/} $inputString]
puts "slash count is $count"
The regexp
command usually returns the number of times it has matched things, effectively a boolean without -all
, but useful in this case. (It can returns the details of what it matched with the -inline
option, but in this case we don't care about that.)
Count the number of items that /
characters separate with split
and llength
:
set count [llength [split $inputString "/"]]
puts "chunk count is $count"
This reports one more than the method with regexp
.
I've not time
d either of these approaches.
If these are filenames, use file split
instead.
set count [llength [file split $inputFilename]]
That handles some edge cases in filename parsing that you are almost certainly ignorant of. (I know I'm ignorant of many of them too… which is why I'm happy to have the file split
command take care of it.)
Upvotes: 0
Reputation:
The quickest solution is:
set item "Sss/jjk/gyii/fff"
set depth [llength [split $item {/}]]
Upvotes: 1