C/C++ >> How to separate a String
Posted by susenad on 23:01:00 09-09-2003
Hi Everybody
I habe a small Problem.
In my Code i became the following variable
xmlChar *fitness;
fitness = xmlstrdup(xmlLDAPGetValue(cxt,result));
with the Value ie (alpha;beta) where alpha and beta are int or double Value.
How can i separate them.
I want something like
fitness[1] = alpha;
fitness[2] = beta;
We don't have to forget that the String ist "(alpha;beta)"


hier is the Code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
char *fitness[2];
char *ptr, *ptr2;
char temp[10], temp2[10];
double fitnessvalue;
int fitnesshaeufig;

/* Find out the terminator positions */
ptr = strstr(*fitness, ";");
ptr2 = strstr(ptr, ")");
/* Put null terminators temporarily */
*ptr = '\0'; *ptr2 = '\0';

/* Now copy the strings to temp buffers */
strcpy(temp, &fitness[1]);
strcpy(temp2, ptr + 1);

/* undo the null terminators */
*ptr = ';';
*ptr2 = ')';

/* Convert the two strings to the respective types */
fitnessvalue = atof(temp);
fitnesshaeufig = atoi(temp2);
*fitness[1]= fitnessvalue; /* should i write this??*/
*fitness[2]= fitnesshaeufig;

printf("\n The FitnessValue : ");
scanf("%g\n", &fitnessvalue);
printf("\n The FitnessHaeufig: ");
scanf("%d\n", &fitnesshaeufig);

if ("NULL" == fitness[1]|| "NULL" == fitness[2])//It is not working hier!!!
return(1.0);
else{
printf("%g\n%d\n", fitnessvalue, fitnesshaeufig);}

return 0;
}

[ This Message was edited by: dxprog on 2003-09-09 23:40 ]
Posted by dxprog on 05:27:00 09-10-2003
I'm not sure if this applies to C, but in PHP there is an explode function that will split up a string by the provided delimeter. Example:

myString = "thing1;thing2";
myArray = explode (";", myString);
myArray would then be:
myArray[0] = "thing1"
myArray[1] = "thing2"

I hope that helps a little (and I hope C supports that function ) [addsig]
Posted by cowsarenotevil on 06:14:00 09-10-2003
I'm not sure there's an "explode"-like statement in C, but there are a lot of string functions in the cstring library (you can also use STD strings, rather than arrays of characters, but that's aside the point). If there isn't one though, you could use a loop to read each character and check if it's reached the character you wish to split it at, and then devide it correctly from there.
Posted by PGuard on 07:16:00 09-10-2003
This will do the trick:

Code:
char *first,*second;
char *string="thing1;thing2";

first=strdup(string);
second=strchr(first,';');
*second='\0';
++second;


EDIT: some weird problem...\0 == \\0


[ This Message was edited by: PGuard on 2003-09-10 07:44 ]
Posted by split on 07:21:00 10-01-2003
That's a PHP problem.