我有一个功课,要求我们从用户那里取一个文本(sting)并逐行分开; 我一直在想但我无法做出正确的事情,我想我需要使用指针
例如:
Each shape has properties, AND //
each shape may be drawn with a//
different Char.
这个文本必须从(//)中分离出来我需要找到给出行数的算法:3。
答案 0 :(得分:1)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char *text = "Each shape has properties, AND //each shape may be drawn with a//different Char.";
size_t len = strlen(text);
char **separated_text = malloc(((len+2)/3)*sizeof(char *));
char *p;
int i, n=0;
for(;;){
if(p = strstr(text, "//")){
len = p - text + 2;// 2 == strlen("//")
separated_text[n] = malloc(len+1);
memcpy(separated_text[n], text, len);
separated_text[n++][len] = 0;
text += len;
} else {
len = strlen(text);
separated_text[n] = malloc(len+1);
strcpy(separated_text[n++], text);
break;
}
}
for(i=0; i<n; ++i){
puts(separated_text[i]);
free(separated_text[i]);
}
free(separated_text);
return 0 ;
}