tsplit_into_seq.nim 803 B

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