Casper_Rene
Casper_Rene

Reputation: 1

How to search number of backslash

I have a string like below and I want to know the depth

  1. Assb/vvv/jjj
  2. 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

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137567

There are a few ways. Here are two that count slightly different things:

  1. 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.)

  2. 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 timed 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

user15498903
user15498903

Reputation:

The quickest solution is:

set item "Sss/jjk/gyii/fff"
set depth [llength [split $item {/}]]

Upvotes: 1

Related Questions