Ooops
November 28, 2020, 02:55:47 AM

Author Topic: [bmx] Create a string by repeating a string by N [ 1+ years ago ]  (Read 726 times)

Offline BlitzBot

  • Jr. Member
  • **
  • Posts: 1
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
  1. // repeatstring.c
  2. #include <brl.mod/blitz.mod/blitz.h>
  3.  
  4. BBString *StringByRepeatingString(BBString const *str, int const length) {
  5.         BBString *repString = bbStringNew(length);
  6.         BBChar *buf = repString->buf;
  7.         unsigned int idx = 0;
  8.         if ( str == &bbEmptyString )
  9.         {
  10.                 for (; idx < length; ++idx)
  11.                         buf[idx]=L' ';
  12.         }
  13.         else if ( str->length == 1 )
  14.         {
  15.                 BBChar character = str->buf[0];
  16.                 for (; idx < length; ++idx)
  17.                         buf[idx] = character;
  18.         }
  19.         else
  20.         {
  21.                 int slen = str->length;
  22.                 BBChar const *inpBuf = str->buf;
  23.                 for (; idx < length; ++idx)
  24.                         buf[idx] = inpBuf[idx%slen];
  25.         }
  26.         return repString;
  27. }
  28.  
  29.  
  30. ' BlitzMax
  31. Import "repeatstring.c"
  32.  
  33. Extern "C"
  34.     Function StringByRepeatingString:String(str:String, length%)
  35. 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.


 

SimplePortal 2.3.6 © 2008-2014, SimplePortal