This is supposed to be strict ANSI C89 pedantic code. It should extract word1
, word2
and word3
from a string formatted [ word1 ] word2 [ word3 ] and return failure in any other format.
It seems to work, but it seems so ugly. No need to comment about the fact GetTokenBetweenSquareBraces
and GetTokenBtweenOpositeSquareBraces
are duplicates.
I would love some tips on how to clean this up.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char * TrimWhiteSpaces(char *str) {
char *out = str;
int i;
int len = strlen(str);
for (i=0; i<len && isspace(str[i]); i++, out++); /*scan forward*/
for (i=len-1; i>=0 && isspace(str[i]); str[i]=0, i--);/*scan backward*/
return out;
}
char * GetTokenBetweenSquareBraces(char * input, char **output, int * output_size) {
char *p = TrimWhiteSpaces(input);
*output_size=0;
if (p[0] == '[')
{
*output = TrimWhiteSpaces(p + 1);
do
{
(*output_size)++;
}while((*output)[*output_size] != ']' && isalnum((*output)[*output_size]));
}
else
{
return NULL;
}
return (*output) + *output_size;
}
char * GetTokenBtweenOpositeSquareBraces(char * input, char **output, int * output_size) {
char *p = TrimWhiteSpaces(input);
*output_size=0;
if (p[0] == ']')
{
*output = TrimWhiteSpaces(p + 1);
do
{
(*output_size)++;
}while((*output)[*output_size] != '[' && isalnum((*output)[*output_size]));
}
else
{
return NULL;
}
return (*output) + *output_size;
}
int GetWords(char * str,char * word1,char * word2,char * word3)
{
char * next=NULL,*output=NULL;
int outputsize;
printf ("\nSplitting string \"%s\" into tokens:\n",str);
next = GetTokenBetweenSquareBraces (str,&output,&outputsize);
strncpy(word1,output,outputsize);
word1[outputsize] = '\0';
strcpy(word1,TrimWhiteSpaces(word1));
if(!next) return 0;
next = GetTokenBtweenOpositeSquareBraces (next,&output,&outputsize);
strncpy(word2,output,outputsize);
word2[outputsize] = '\0';
strcpy(word2,TrimWhiteSpaces(word2));
if(!next) return 0;
next = GetTokenBetweenSquareBraces (next,&output,&outputsize);
strncpy(word3,output,outputsize);
word3[outputsize] = '\0';
strcpy(word3,TrimWhiteSpaces(word3));
if(!next) return 0;
return 1;
}
void TestGetWords(char * str )
{
char word1[20],word2[20],word3[20];
if (GetWords(str,word1,word2,word3))
{
printf("|%s|%s|%s|\n",word1,word2,word3);
}
else
{
printf("3ViLLLL\n");
}
}
int main (void)
{
char str[] ="[ hello ] gfd [ hello2 ] ";
char str2[] ="[ hello [ gfd [ hello2 ] ";
char str3[] ="the wie321vg42g42g!@#";
char str4[] ="][123[]23][231[";
TestGetWords(str);
TestGetWords(str2);
TestGetWords(str3);
TestGetWords(str4);
getchar();
return 1;
}