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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
char *str_sub (const char *s, size_t start, size_t end)
{
char *new_s = NULL;
/* attention aux valeurs incoherentes... */
if (s != NULL && start <= end && end <= strlen (s))
{
size_t new_len = end - start + 1;
new_s = malloc (sizeof *new_s * (new_len + 1));
if (new_s != NULL)
{
size_t i;
/* mettre le defaut en evidence */
memset (new_s, '?', (new_len + 1));
for (i = start; i < end; i++)
{
assert (i - start < new_len);
new_s[i - start] = s[i];
}
/* correction */
assert (i - start <= new_len);
new_s[i - start] = 0;
}
}
return new_s;
}
int main (void)
{
char const *ch1 = "bonjour";
struct test
{
int num;
struct
{
int start;
int end;
}
in;
struct
{
char const *s;
}
out;
};
/* *INDENT-OFF* */
static struct test const a[] =
{
{10, {0, 0}, {"" }},
{11, {0, 1}, {"b" }},
{12, {0, 7}, {"bonjour"}},
{20, {1, 6}, {"onjou" }},
{21, {6, 7}, {"r" }},
{22, {6, 6}, {"" }},
{23, {7, 7}, {"" }},
{30, {0, -1}, {NULL}},
{31, {-1, 0}, {NULL}},
{32, {0, 8}, {NULL}},
{33, {7, 8}, {NULL}},
{34, {8, 8}, {NULL}},
{35, {5, 4}, {NULL}},
};
/* *INDENT-ON* */
size_t i;
int err = 0;
for (i = 0; i < sizeof a / sizeof *a; i++)
{
struct test const *p = a + i;
char *sub = str_sub (ch1, p->in.start, p->in.end);
if (sub != NULL)
{
if (p->out.s != NULL)
{
if (strcmp (sub, p->out.s) != 0)
{
printf ("error at test #%d (str_sub(%s, %d, %d) = '%s')\n",
p->num, ch1, p->in.start, p->in.end, sub);
err = 1;
}
}
else
{
printf ("error at test #%d (str_sub(%s, %d, %d) = '%s')\n",
p->num, ch1, p->in.start, p->in.end, sub);
err = 1;
}
free (sub), sub = NULL;
}
else
{
if (sub != p->out.s)
{
printf ("error at test #%d (str_sub(%s, %d, %d) = '%s')\n",
p->num, ch1, p->in.start, p->in.end, sub);
err = 1;
}
}
assert (sub == NULL);
}
if (!err)
{
puts ("P A S S E D");
}
return 0;
} |
Partager