This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Feb 26th, 2012  |  syntax: C  |  size: 1.40 KB  |  views: 21  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. typedef struct{
  2.         int nSize;
  3.         int nMaxCapacity;
  4.         char* szStr;
  5. } StringBuilder;
  6.  
  7. StringBuilder* Initialize(int nCapacity);
  8. void Append(StringBuilder *strBuilder, char* szStr);
  9. void Clear(StringBuilder *strBuilder);
  10.  
  11. int _tmain(int argc, _TCHAR* argv[])
  12. {
  13.         StringBuilder* strBuilder = Initialize(1);
  14.         Append(strBuilder, "I'm the string! :)\0");
  15.         printf("%s", strBuilder);
  16.         Clear(strBuilder);
  17.  
  18.         getchar();
  19.  
  20.         return 0;
  21. }
  22.  
  23. StringBuilder* Initialize(int nCapacity)
  24. {
  25.         StringBuilder* strBuilder = (StringBuilder*)malloc(sizeof(StringBuilder));
  26.         strBuilder->nMaxCapacity = nCapacity;
  27.         strBuilder->nSize = 0;
  28.         strBuilder->szStr = (char*)malloc(1);
  29.         strBuilder->szStr = "\0";
  30.  
  31.         return strBuilder;
  32. }
  33.  
  34. void Clear(StringBuilder *strBuilder)
  35. {
  36.         if(strBuilder != NULL)
  37.                 free(strBuilder);
  38. }
  39.  
  40. void Append(StringBuilder *strBuilder, char* szStr)
  41. {
  42.         if(strBuilder->nSize + strlen(szStr) > strBuilder->nMaxCapacity)
  43.                 if((strBuilder->nMaxCapacity * 2) <= 2147483647)
  44.                 {
  45.                         strBuilder = (StringBuilder*)realloc(strBuilder, (strBuilder->nMaxCapacity * 2));
  46.                         strBuilder->nMaxCapacity = strBuilder->nMaxCapacity * 2;
  47.                 }
  48.                 else
  49.                         return; // overflow
  50.         else
  51.                 strBuilder = (StringBuilder*)realloc(strBuilder, strBuilder->nSize + strlen(szStr));
  52.  
  53.         strBuilder->nSize += strlen(szStr);
  54.         strBuilder->szStr = (char*)realloc(strBuilder->szStr, strBuilder->nSize + 2);
  55.  
  56.         strcat(strBuilder->szStr, szStr);
  57. }
clone this paste RAW Paste Data