# substr() like in PHP
proc substr*(str: string, start: int, length: int): string =
var o = start
var n = length
if n < 0 and -n > str.len:
return "" # or nil?
elif n > str.len:
n = str.len
if o > str.len:
return "" # or nil?
elif o < 0 and -o > str.len:
o = 0
if n < 0 and n + str.len - o < 0:
return "" # or nil?
# offset from end of string
if o < 0:
o = str.len + o;
if o < 0:
o = 0
# negative length cuts the string
if n < 0:
n = str.len - o + n
if n < 0:
n = 0
if o + n > str.len:
n = str.len - o
str[o ..< o + n]
proc substr*(str: string, start: int): string =
substr(str, start, str.len)
when isMainModule:
var test = "Test.xml"
assert(test.substr(0) == "Test.xml")
assert(test.substr(0,8) == "Test.xml")
assert(test.substr(0,0) == "")
assert(test.substr(0,1) == "T")
assert(test.substr(1) == "est.xml")
assert(test.substr(-1) == "l")
assert(test.substr(0,-4) == "Test")
assert(test.substr(7,1) == "l")
assert(test.substr(-3) == "xml")
assert(test.substr(-4,1) == ".")
assert(test.substr(-100,2) == "Te")
assert(test.substr(8) == "")