This simple program was created in TurboC++ explorer and is used to do the job.
But i have a question on my own. Why when i use the delimiter '\' to search for that character it doesn work? It says that the character is not found? I used the value 0x5c too as is in ASCII table and nothing, though it works for every other character, i surely miss something, give me your thoughts on that.
Code:
//---------------------------------------------------------------------------
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#pragma hdrstop
//---------------------------------------------------------------------------
//Function SplitString splits a string according to user input.
char *SplitString(const char *mainString, const char delimiter)
{
if(mainString == NULL)
{
printf("Can not split an empty string.\n");
return NULL;
}
else
{
//Index.
int ptrIndex = 0;
//Size of the return string.
int ptrSize = 0;
//The return string.
char *ptrString = NULL;
//Strrchr pointer.
char *ptrStr = NULL;
//Find the last occurance of delimiter in main string.
if((ptrStr = strrchr(mainString, delimiter)) == NULL)
{
printf("Error, Can not find the '%c' delimiter in main string.\n", delimiter);
return NULL;
}
else
{
ptrIndex = mainString - ptrStr;
ptrIndex = ptrIndex > 0 ? ptrIndex : -ptrIndex;
//Go to the next character.
ptrIndex++;
//Save size.
ptrSize = (int)strlen(mainString) - ptrIndex;
//Get space.
ptrString = calloc(ptrSize + 1, sizeof(char));
strcpy(ptrString, &mainString[ptrIndex]);
//Return the string.
return ptrString;
}
}
}
#pragma argsused
int main(int argc, char* argv[])
{
char *mString = "C:\Documents and Settings\myfile.txt";
char del = 's';
char *r = SplitString(mString, del);
printf("Final String: %s\n", r);
printf("Hit any key to exit........");
getch();
return 0;
}
//---------------------------------------------------------------------------