[bmx] Create a string by repeating a string by N [ 1+ years ago ]

Started by BlitzBot, June 29, 2017, 00:28:43

Previous topic - Next topic

BlitzBot

Title : Create a string
Author : repeating a string by N
Posted : 1+ years ago

Description : This is a function to avoid the (to me) annoying method of repeatedly concatenating a string, thus allocating a bunch of new strings every time you want to repeat a string.  So, I wrote this quick bit of code in C to alleviate that problem.  It only allocates one string, the end result, and repeatedly copies the passed string's contents until full.

There are probably other optimizations that can be made, but for the sake of just improving on the speed of concatenating strings and other methods limited to BlitzMax (this code can actually be implemented in BlitzMax with some minor hacking, but it's slower as a result).


Code :
Code (blitzmax) Select
// repeatstring.c
#include <brl.mod/blitz.mod/blitz.h>

BBString *StringByRepeatingString(BBString const *str, int const length) {
BBString *repString = bbStringNew(length);
BBChar *buf = repString->buf;
unsigned int idx = 0;
if ( str == &bbEmptyString )
{
for (; idx < length; ++idx)
buf[idx]=L' ';
}
else if ( str->length == 1 )
{
BBChar character = str->buf[0];
for (; idx < length; ++idx)
buf[idx] = character;
}
else
{
int slen = str->length;
BBChar const *inpBuf = str->buf;
for (; idx < length; ++idx)
buf[idx] = inpBuf[idx%slen];
}
return repString;
}


' BlitzMax
Import "repeatstring.c"

Extern "C"
    Function StringByRepeatingString:String(str:String, length%)
End Extern


Comments :


Warpy(Posted 1+ years ago)

 I miss python's "hello"*5 syntax.


N(Posted 1+ years ago)

 I prefer Ruby, but to each his own.