1

I was searching for a way to get the length of a string in batch. So I read the answer from jeb which contains some mysterios signs I dont't get.

He uses the pound sign (#) in the function strlen when retrieving the input string:

:strlen <resultVar> <stringVar>
(   
[...]
    set "s=!%~2!#"
[...]
)

Can someone explain what the pound sign means? As far as I understand the !%~2! gives the second parameter from the call. But what is the # used for and why is the expression after SET enclosed in "?

Radinator
  • 1,048
  • 18
  • 58
  • It is best practice to enclose the `SET` command with quotes. It preserves special characters and prevents any trailing spaces you might not see at the end of the command. Why not put a comment below Jeb's answer to ask him the purpose instead of asking your question. He comes here often and will probably answer you within the day. – Squashman Oct 26 '18 at 15:39
  • Following a `:label` and a space can be any information - it is ignored. Here it denotes what arguments the subroutine/function expects: ` ` both by refefernce. The appended `#` is IMO there to convert the zero based offset calculation to a length by adding one char. –  Oct 26 '18 at 16:09
  • `#` has no special meaning. It's just a character, like `a`. The `set` command just appends that character to a given string (probably for the reason, LotPings mentioned). – Stephan Oct 26 '18 at 16:12
  • `dostips` has a related [:strlen function](https://www.dostips.com/DtCodeCmdLib.php#Function.strLen) (with reversed arguments) I don't know which one is more efficient/faster. –  Oct 26 '18 at 16:22
  • 1
    @LotPings, I believe Jeb's is faster if my memory serves me. I know it was discussed on DosTips some years ago. – Squashman Oct 26 '18 at 16:31
  • 1
    Dbenham did an in depth speed test of all the common algorithms used on [SS64](https://ss64.org/viewtopic.php?pid=6478#p6478) – Squashman Oct 26 '18 at 16:39
  • @Squashman The difference between the binary variants seems neglible - but that the tempfile approach is best - is hmm.. disappointing. –  Oct 26 '18 at 17:44

1 Answers1

1

I used the hash character # in the strlen function to solve two problems.

Splitting a variable with the :~n,m snytax fails for empty(undefined) variables, appending a character prevents that problem.

And the result of the algorithm is the string length minus one of the s variable, by appending a character compensate the result.

Why I used the hash?
The only reason I can remember is to use a character without any special batch functionality and it is good visible.

jeb
  • 78,592
  • 17
  • 171
  • 225