/******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, PHP, Ruby,
C#, VB, Perl, Swift, Prolog, Javascript, Pascal, HTML, CSS, JS
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
#include <stdio.h>
#include <string.h>
// if output is not NULL this will take an input and a delimiter
// and construct a NUL terminated set of NUL terminated strings into output
// and return the size of the whole thing
//
// if output is not NULL this will only calculate how much space would be used
// and then return the size of the whole thing
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
}
int main()
{
{
char input[100] = "A89 99B0 C11D98 9\0abcdefghijklmn";
char delimiters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// count the size of the output string
long size = tokenise(NULL,input,delimiters);
printf("size = %ld\n",size);
}
puts("");
{
char input[100] = "A89 99B0 C11D98 9\0abcdefghijklmn";
char delimiters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char output[100] = "1234567890123456789012345678901234567890";
// tokenise the input to output
long size = tokenise(output,input,delimiters);
printf("size = %ld\n",size);
// now print the strings
char *pointer = output;
while(*pointer)
{
puts(pointer);
pointer += strlen(pointer)+1;
}
}
puts("");
{
char input[100] = "A89 99B0 C11D98 9\0abcdefghijklmn";
char delimiters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// tokenise the input in place
long size = tokenise(input,input,delimiters);
printf("size = %ld\n",size);
// now print the strings
char *pointer = input;
while(*pointer)
{
puts(pointer);
pointer += strlen(pointer)+1;
}
}
return 0;
}