tsplit_into_openarray.nim 741 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. discard """
  2. output: '''asdf
  3. 231
  4. '''
  5. cmd: "nim c --gc:arc -d:useMalloc -g $file"
  6. valgrind: true
  7. """
  8. {.experimental: "views".}
  9. const
  10. Whitespace = {' ', '\t', '\n', '\r'}
  11. iterator split*(s: string, seps: set[char] = Whitespace,
  12. maxsplit: int = -1): openArray[char] =
  13. var last = 0
  14. var splits = maxsplit
  15. while last <= len(s):
  16. var first = last
  17. while last < len(s) and s[last] notin seps:
  18. inc(last)
  19. if splits == 0: last = len(s)
  20. yield toOpenArray(s, first, last-1)
  21. if splits == 0: break
  22. dec(splits)
  23. inc(last)
  24. proc `$`(x: openArray[char]): string =
  25. result = newString(x.len)
  26. for i in 0..<x.len: result[i] = x[i]
  27. proc main() =
  28. for x in split("asdf 231"):
  29. echo x
  30. main()