tsplit_into_table.nim 795 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. discard """
  2. output: '''5: 231
  3. 0: asdf
  4. '''
  5. """
  6. import tables
  7. {.experimental: "views".}
  8. const
  9. Whitespace = {' ', '\t', '\n', '\r'}
  10. proc split*(s: string, seps: set[char] = Whitespace,
  11. maxsplit: int = -1): Table[int, openArray[char]] =
  12. var last = 0
  13. var splits = maxsplit
  14. result = initTable[int, openArray[char]]()
  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. result[first] = 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. let words = split("asdf 231")
  29. for i, x in words:
  30. echo i, ": ", x
  31. main()