Code archives/Algorithms/Create a string by repeating a string

This code has been declared by its author to be Public Domain code.

Download source code

Create a string by repeating a string by N2009
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).
// 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

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


N2009
I prefer Ruby, but to each his own.


Code Archives Forum