[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Why (substring "abc" 0 4) does not return "abc" instead of an error?

From: Dmitry Gutov
Subject: Re: Why (substring "abc" 0 4) does not return "abc" instead of an error?
Date: Mon, 16 Jul 2012 23:00:44 +0400
User-agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:13.0) Gecko/20120614 Thunderbird/13.0.1

Tassilo Horn <address@hidden> writes:
> BTW: C++ string's substr method doesn't quite have the suggested
> behavior.  It's arguments are not two indices, but one index and one
> length n (the number of characters that should be returned).  If the
> index is out of range, you'll get an out_of_range exception.  n however
> may span longer than the rest of the string in which case the returned
> string is shorter than the given length n.  But that's a different
> story: indexes have to be in range.
> Ditto for Ruby: String::slice also gets an index and a length, not two
> indices.

True, but it also accepts range as parameter. Neither form
raises error:

irb(main):007:0> "abc".slice(1, 10)
=> "bc"
irb(main):008:0> "abc".slice(0..1)
=> "ab"

Same thing with JavaScript:

[22:51:01.141] "abc".substring(0,1)
[22:51:01.147] "a"
[22:51:03.341] "abc".substring(1,2)
[22:51:03.345] "b"
[22:51:13.902] "abc".substring(1,20)
[22:51:13.905] "bc"
[22:52:00.768] "abc".substr(2,1)
[22:52:00.772] "c"

So far I don't see another language, aside from Emacs Lisp, that
interprets negative value of second index as "count from the end", yet
raises an "out of range" error if that value is too big.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]