我有一个char *:
char* version = "10.5.108";
我希望通过char分隔符获得两个新的char *。
char delimiter = '.';
执行以下代码后的代码:
printf("|%s|%s|", first, second);
应该导致:
|10|5.108|
答案 0 :(得分:0)
抓住:!)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
int main(void)
{
char *version = "10.5.108";
char *first, *second;
if ( ( second = strchr( version, '.' ) ) == NULL )
{
first = malloc( strlen( version ) + 1 );
strcpy( first, version );
second = malloc( sizeof( char ) );
*second = '\0';
}
else
{
ptrdiff_t n = second - version;
first = malloc( ( n + 1 ) * sizeof( char ) );
second = malloc ( ( strlen( version ) - n ) * sizeof( char ) );
strncpy( first, version, n );
first[n] = '\0';
strcpy( second, version + n + 1 );
}
printf( "|%s|%s|", first, second );
free( first );
free( second );
return 0;
}
输出
|10|5.108|