开发者

How do I convert a string to a list in Io?

For example, I'd like to turn "hello" into list(104, 101, 108, 108, 111) or list("h", "e", "l", "l", "o")

开发者_如何学运维

So far I've created an empty list, used foreach and appended every item to the list myself, but that's not really a concise way to do it.


My own suggestion:

Sequence asList := method(
  result := list()
  self foreach(x,
    result append(x)
  )
)

Haven't tested it performance-wise but avoiding the regexp should account for something.


Another nicely concise but still unfortunately slower than the foreach solution is:

Sequence asList := method (
    Range 0 to(self size - 1) map (v, self at(v) asCharacter)
)


One way would be to use Regex addon:

#!/usr/bin/env io

Regex

myList := "hello" allMatchesOfRegex(".") map (at(0))

But I'm sure there must be other (and perhaps even better!) ways.


Update - re: my comment in question. It would be nice to have something built into Sequence object. For eg:

Sequence asList := method (
    Regex
    self allMatchesOfRegex(".") map (at(0))
)

# now its just
myList := "hello" asList


I have Io Programming Language, v. 20110905 and method asList is defined by default, so you can use it without any new definitions. Then you can get char codes with map method.

Io 20110905
Io> a := "Hello World"
==> Hello World
Io> a asList
==> list(H, e, l, l, o,  , W, o, r, l, d)
Io> a asList map(at(0))
==> list(72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜