ID:169371
 
Hello BYOND!

From the depths of ThorgSphere R&D comes a question:

if I have a text string, TEXT, and wanted to dissect it down into the letters that makes it up one by one. How would I do this? For example:

for(Letter in TEXT)
messwithLetterHere = 1


The above is just to show what I'd like to do.
So, say if TEXT = "HELLO!"

Then I'd like aq proc that could run through the letters in TEXT. Let's say the proc outputted the letter. I'd want something that would output:

H
E
L
L
O
!

Any questions needed to help answer this will be posted A.S.A.P by me upon request.
Thanks in advance.

-Thorg
To pull a single character out of a string, use text2ascii(). You may think that copytext() would be better, but while you can use copytext() to pull a single character out of a string, text2ascii() is a lot faster.

proc/output_characters_seperately(string)
for(var/pos = 1 to length(string))
world << ascii2text(text2ascii(string,pos))
mob/verb/Breakdown(T as text)
for(var/i = 1, i<=length(T), i++)
world << copytext(T,i,i+1)


Look up for loops if you don't understand how that works.

*Edit*

Ok listen to Wiz instead.
In response to Wizkidd0123
Wiz I tried profiling the world to see whose is faster but they both came out with the excat same time. Here's what I was doing:

mob/verb/Break(T as text)
output_characters_seperately(T)

proc/output_characters_seperately(string)
for(var/pos = 1 to length(string))
world << ascii2text(text2ascii(string,pos))

mob/verb/Breakdown(T as text)
for(var/i = 1, i<=length(T), i++)
world << copytext(T,i,i+1)


I tried both short and long strings.
In response to DeathAwaitsU
That's most likely because you can't see the difference because most of the time is used to output text. To get a nice measurement I like to run a proc a good number of times repeatedly, and of course outputting text to the world when I do that isn't a good idea. Use this case; the trash variable is going to give you warnings, but it should demonstrate the speed difference nicely. =)

mob/verb/Break(T as text)
for(var/counter=1 to 3000)
output_characters_seperately(T)
for(var/counter=1 to 3000)
Breakdown(T)

proc/output_characters_seperately(string)
for(var/pos = 1 to length(string))
var/trash= ascii2text(text2ascii(string,pos))

proc/Breakdown(string)
for(var/pos = 1 to length(string))
var/trash= copytext(string,pos,pos+1)


Please note that it's important to make everything the same besides what you're trying to test (your for loop setup is what I'm refering to).
In response to Wizkidd0123
The reason why text2ascii is faster is that you aren't building a new string which is very time saving however by converting the value back to a string you've killed your boost. Since there are a very finite number of characters in may be best to throw them in a lookup table and use that.