1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| char *str_subs(const char *s, unsigned int start, unsigned int end) {
char *str;
int i;
str = NULL;
if (s != NULL && start < end) {
str = (char *) malloc(sizeof(char) * (end - start + 2));
if (str != NULL) {
for (i = 0; i <= end; i++) {
str[i - start] = s[i];
}
str[i] = '\0'; // j ai rajouter ceci pour mettre le caractere de fin.
}
else {
fprintf(stderr, "error malloc(): not enough memmory.\n");
exit(EXIT_FAILURE);
}
}
return str;
}
int main() {
char *s = "qwertyuiop";
char *ss = str_subs(s, 0, 3);
printf("ss : %s %d\n", ss, strlen(ss));
s = str_subs(s, 4, 10);
printf("\ns : %s %d\n", s, strlen(s));
printf("ss : %s %d\n", ss, strlen(ss));
printf("\nss : %s %d\n", ss, strlen(ss));
free(ss);
printf("%s\n%d\n", s, strlen(s));
free(s);
} |
Partager