因为一次面试,给我出的一道题目:
#include <stdio.h>
#include <stdlib.h>#include <string.h>
#define MAXSIZE 124
int split_n( char *, char **,char ) ;
int main(int argc, char **argv)
{
int Return_Num = 0 ;
int r_len ;
int n ;
char string_n[MAXSIZE] ;
char **toString = NULL ;
toString = (char**)malloc(124*sizeof(char*)); // 这里要注意给toString 分配空间
printf ( "Please wirte:\n" ) ;
fgets(string_n, MAXSIZE, stdin) ;
r_len = strlen (string_n) ;
string_n[r_len-1] = '\0' ; // 因为fgets是'\n'结尾的而不是'\0',所以做一个替换
Return_Num = split_n (string_n, toString, ' ') ;
for (n=0; n<=Return_Num; n++)
{
printf ("%s\n",toString[n]) ;
}
return 0 ;
}
int split_n( char *from, char **to, char separator )
{
int R_num = 0 ;
int n = 0 ;
int up = 0 ;
char *temp = NULL ;
char *from_back = from ;
while (*from_back != '\0')
{
n++ ;
if (*from_back == separator)
{
temp = (char *)malloc( n ) ;
strncpy ( temp, from+up, n ) ;
up += n ;
temp[n] = '\0' ;
*to = temp ;
*(to++) ;
R_num++ ;
n = 0 ;
}
from_back++ ;
}
if (n > 0)
{
temp = (char *)malloc( n ) ;
strncpy ( temp, from+up, n ) ;
temp[n] = '\0' ;
*to = temp ;
}
return R_num ;
}