C++ Builder

La Isla Bonita



Split Function
Split Function


Description

This article describes the Split function. This function splits a C string into a given number of substrings (AnsiStrings) by using a delimeter. The C String has the following form:
char* s = "s1ds2ds3ds4ds5d..."
Where s1, s2, s3, s4, etc are substrings and d is the delimiter character that is used to separate the substrings.

Split.cpp


#include <vcl.h>
#pragma hdrstop

#include "Split.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------

class SplitString
{
  public:
    String A;
};


int Split( char* s, char Delimiter, SplitString* p )
{
    int i = 0;
    int ObjectIdx = 0;

    while ( s[i] != '\0' )
    {
        if ( s[i] != Delimiter )
        {
            (p + ObjectIdx)->A += String( s[i] );
        }
        else
        {
           ObjectIdx++;
        }
        i++;
    }
    return ObjectIdx + 1;
}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
   //String we want to split
   char* S = "hello wonderful world";

   String R;
   int TotalSubStrings;   //Use for testing only

   SplitString o[100];
   SplitString* pSplit = &o[0];

   //USAGE
   TotalSubStrings = Split( S , ' ', pSplit);   
   
   //TEST----------------------------------------
   for ( int i=0; i< TotalSubStrings; i++ )
   {
       R += (pSplit+i)->A;
       ShowMessage( (pSplit+i)->A );
   }
   ShowMessage( String(TotalSubStrings) );
   //END OF TEST---------------------------------
}

Split.h

#ifndef SplitH
#define SplitH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:	// IDE-managed Components
        TButton *Button1;
        void __fastcall Button1Click(TObject *Sender);
private:	// User declarations
public:		// User declarations
        __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif

Homepage

Copyright © 1997-2002 Rodolfo A. Frino. All rights reserved.