Generating a string of arbitrary length

wick

Member
3rd Party Module Dev
Tutorial Author
Patreon Bronze
Joined
Jul 17, 2017
Messages
76
I've run into a case where I need to generate a string of X length and was surprised that I didn't actually know a quick way to do it in CX. Only way I know how would be with a loop:

Code:
Local string$
For Local i% = 0 Until 32
  string = string + "A"
Next

Anyone know of a more elegant/memory-efficient way? E.g. in Ruby you can just go "A" * 32
 

MikeHart

Administrator
Joined
Jun 19, 2017
Messages
3,167
Not sure if it is more elegant or memory efficient but this one:


Code:
Local s:String = String.FromChars( [65,66,67,32,48,60] )
 

dawlane

Well-known member
CX Code Contributor
Joined
Jun 21, 2017
Messages
855
Behind the scenes, Ruby will covert the "A"*32 into a loop to generate a string of characters.
The question to be asking, would it be faster to deal directly with strings or deal directly with an array to convert to a string after.
All this depends on how efficient Mr S made the native core string and array handling classes.
 

Jimmy

Active member
3rd Party Module Dev
Tutorial Author
Joined
Jan 2, 2020
Messages
922
You could do this, just have some string laying around that is long enough :

Code:
Strict

Function Main:Int()

     Local a:String = "0123456789abcdefghijklmnopqrstuvwxyz"
    Local b:String = ""

      ' Create string b with some length
     Local IWantLength:Int = 10
     b = Mid(a,1,IWantLength)

' This would do the same :
' b = a[(0)..(IWantLength)]

     Print b

    Return 0        
End


Function Len:Int(s:String)
    Return s.Length
End

Function Mid:String(s:String,p:Int,n:Int)
    p=p-1
    Return s[(p)..(p+n)]
End
 
Last edited:

wick

Member
3rd Party Module Dev
Tutorial Author
Patreon Bronze
Joined
Jul 17, 2017
Messages
76
Ha! That's very creative, I like it. Yeah, there's a max length that I might ask for in my case (showing asterixes in place of characters in a password text field), so I could just pre-make a long string of them and slice it. Thanks!
 

Gerry Quinn

Active member
Tutorial Author
Joined
Jun 24, 2017
Messages
153
FromChars is the way to go. If you know the length in advance you can use an array, if not you can use a Stack to get a sort of StringBuffer.
 
Top Bottom