split string into array c

7 views
Skip to first unread message

Lydia

unread,
Jun 1, 2012, 2:13:13 AM6/1/12
to embeded...@googlegroups.com


#include <string.h>

char str[] = "now / is the time for all / good men to come to the / aid of their country";
char delims[] = "/";
char *result = NULL;
result = strtok( str, delims );
while( result != NULL ) {
printf( "result is \"%s\"\n", result );
result = strtok( NULL, delims );
}

OUTPUT:
result is "now "
result is " is the time for all "
result is " good men to come to the "
result is " aid of their country"

許尚偉

unread,
Jun 7, 2012, 8:34:25 PM6/7/12
to embeded...@googlegroups.com
去除空白

char *trimwhitespace(char *str)
{
  char *end;

  // Trim leading space
  while(isspace(*str)) str++;

  if(*str == 0)  // All spaces?
    return str;

  // Trim trailing space
  end = str + strlen(str) - 1;
  while(end > str && isspace(*end)) end--;

  // Write new null terminator
  *(end+1) = 0;

  return str;
}

temp = strtok( input, '/');
while(temp != NULL){
    result = trimwhitespace(temp);
    temp = strtok('/');
}


Lydia於 2012年6月1日星期五UTC+8下午2時13分13秒寫道:
Reply all
Reply to author
Forward
0 new messages