11-03-2016 01:18 PM
What is the most efficient way to generate a string of a pre-set length using padding with white spaces when necessary?
For example, I have first string = "short string" (12 characters including a space) and I want to convert it into second string "short string ", 16 characters long, white space (or any other character) padded. I would like to have a pre-set length of the second string regardless of the length of the first string. Can I do that efficiently, without loops?..
Solved! Go to Solution.
11-03-2016 01:22 PM - edited 11-03-2016 01:26 PM
1. Initialize Array to create an array of U8 based on whatever length you want. A space would be 32, or 0x20.
2. Byte Array To String (which is basically a no-op)
3. Replace String Subset to replace the first X elements of your new string with the old string, where X is the length of the old string.
11-03-2016 01:27 PM
Thank you!
11-03-2016 01:27 PM - edited 11-03-2016 01:28 PM
Yes. Use Initialize Array, with the element set to a U8 containing the ASCII code of the space character and length set to the desired string length. Convert your initial string to an array of U8 using String to Byte Array. Use Replace Array Subset to put that into the pre-allocated array of spaces, then convert back to a string using Byte Array to String. Conversions between strings and byte arrays are basically free operations (a string is an array of bytes) so this is efficient despite the conversions.
There are other similar approaches, for example you could subtract the existing string length from the desired string length, allocate an array of that number of spaces, convert to a string, and concatenate the spaces onto the end of the existing string.
EDIT: Looks like I was just a bit too slow to respond, and crossrulz beat me to it with a similar idea.
11-03-2016 01:57 PM
Format Into String is a handy tool for string manipulation.
steve
11-03-2016 01:58 PM
This is the best!!
11-03-2016 02:20 PM
This is the simplest possible way, no doubts!
However, the output string cannot be longer than 4096 characters. The array-based method above though not as elegant, does not have this limitation.
11-04-2016 12:14 AM
> However, the output string cannot be longer than 4096 characters.
Interesting. It seems to be a hard limit and there's no mention of it in the help file.
I was not aware of this so thanks for the information!
steve
01-23-2018 11:27 AM
Thanks was exactly what I was looking for.