Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

string tokenization and array entires

Status
Not open for further replies.

blues77

Programmer
Jun 11, 2002
230
CA
Hello,

I need a way of taking a string of chars including whitespace(which is used as a delimiter) and putting each series of chars into its own cell in an array. for example

a bgf h ds

will be put into the array as {a , bgf, h, ds}. only the chars are entered...not the whitespace. Any help is greatly apprecited.

Mike
 
srtok() is deprecated, the man page has the full details.
I'd still use it though, the alternatives are kind of
hackneyed.

I rolled a solution just to see how it could be done, I'm
embarassed to even post it..but., maybe it will give
you an idea, It has some issues..

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

const char alpha[] = &quot;abcdefghijklmnopqrstuvwxyz&quot;;
int is_alpha(char s);
void strbuild(char *str1);

int main(void) {
char mystr[28] = &quot;t is a tes t o fthe &quot;;

strbuild(mystr);

return 0;
}

int is_alpha(char s) {
int y ,j;

for (y=0 ; y <= strlen(alpha) ; y++) {
if (s == alpha[y]) {
return 1;
}
}

return 0;
}

void strbuild(char *str1) {
int y,flg,stp,prev,m = 0;
char **arra;
char *tmp = NULL;

arra[m] = malloc(8);
strcpy(arra[m],&quot;START&quot;);


for (y=0 ; y < strlen(str1) ; y++) {
tmp = str1;
flg = is_alpha(str1[y]) > 0 ? 1 : 0;
if (!flg) {
stp = y;
m++;
arra[m] = malloc((stp - prev) + 1);
if ((stp - prev) > 0) {
tmp = tmp + prev;
strncpy(arra[m],tmp,(stp - prev));
}
}
prev = stp;
}

for (y = 0 ; y <= m ; y++) {
printf(&quot;Array content %d :: %s\n&quot;,y, arra[y]);
}
}
 
Here is a cleaned up function.
Works fine for linux i386, gcc 3.x.

char **strbuild(char *str1) {
int y,flg,stp,prev,m = 0;
int sz = strlen(str1);
char *arra[sz];
char *tmp = NULL;


arra[m] = malloc(8);
strcpy(arra[0],&quot;START&quot;);

for (y=0 ; y < strlen(str1) ; y++) {
flg = is_alpha(str1[y]) > 0 ? 1 : 0;
tmp = str1;

if (!flg) {
stp = y;
m++;
arra[m] = malloc((stp - prev) + 1);

if ((stp - prev) > 0) {
tmp = tmp + prev;
strncpy(arra[m],tmp,(stp - prev));
}
}

prev = stp;
}
return arra;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top