/******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
long tokenise(char *output, char *input, char *delimiters)
{
long length, size = 0;
char *next, *current = input, *destination = output;
while(next = strpbrk(current+1,delimiters))
{
length = next-current;
if(destination)
{
if(output == input)
strcpy(destination+length+1,next++); // if we are doing it in-place
else
strncpy(destination,current,length); // if we are making a new string
destination[length] = '\0';
destination += length+1;
}
size += length+1; // +1 = single NUL
current = next;
}
length = strlen(current);
// if we are doing it in-place
if(destination)
{
if(output != input)
strncpy(destination,current,length); // if we are making a new string
destination[length] = '\0';
destination[length+1] = '\0';
}
return size+length+2; // +2 = double NUL
}
char* onesteptokenise(char **output, char *input, long input_max, char *delimiters)
{
long size = tokenise(NULL,input,delimiters); // measure the size
if (size<=input_max)
{
// do it in place
*output = NULL;
tokenise(input,input,delimiters);
return input;
}
else
{
// make a new string
*output = malloc(size);
if (*output) tokenise(*output,input,delimiters);
return *output;
}
}
int main()
{
{
char input[] = "A89 99B0 C11D98 9";
char delimiters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *output = NULL;
// tokenise the input into a new string - input isn't large enough
char *pointer = onesteptokenise(&output,input,sizeof(input),delimiters);
// now print the strings
while(*pointer)
{
puts(pointer);
pointer += strlen(pointer)+1;
}
if (output) free(output);
}
puts("");
{
char input[100] = "A89 99B0 C11D98 9";
char delimiters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *output = NULL;
// tokenise the input in place - input is large enough
char *pointer = onesteptokenise(&output,input,sizeof(input),delimiters);
// now print the strings
while(*pointer)
{
puts(pointer);
pointer += strlen(pointer)+1;
}
if (output) free(output);
}
return 0;
}