Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <errno.h>
- #include <ctype.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #if defined(TEST_1)
- const char *input = "1str, 123 gdg1(75); test32 0";
- #elif defined(TEST_2)
- const char *input = "1 str, 123 gdg1(75); test32 0";
- #elif defined(TEST_3)
- const char *input = "str, 123 gdg1(75); test32 0s";
- #elif defined(TEST_4)
- const char *input = "str, 123 gdg1(75); test32 0 s";
- #elif defined(TEST_5)
- const char *input = "str, 123 gdg1(75); test32 1d1 0";
- #elif defined(TEST_6)
- const char *input = "str, 123 gdg1(75); test32 d1d 0";
- #elif defined(TEST_7)
- const char *input = "1 123 1 75 3 1";
- #elif defined(TEST_8)
- const char *input = "a bcd e fg h j";
- #elif defined(TEST_9)
- const char *input = "a";
- #elif defined(TEST_10)
- const char *input = "0";
- #else
- const char *input = "str, 123 gdg1(75); test32 0";
- #endif
- const char *RE = "NUM";
- static char *put_replacement(char *out, const char *r, size_t len)
- {
- memcpy(out, r, len);
- return out + len;
- }
- static void replace(const char *in, char *out, size_t outlen)
- {
- const char *q;
- int flag = 0;
- char p;
- while ((p = *in++)) {
- if (flag == 0) {
- if (isdigit(p)) {
- q = in - 1;
- flag = 1;
- continue;
- }
- if (isalpha(p))
- flag = 2;
- }
- if (flag == 1) {
- if (isdigit(p))
- continue;
- if (isalpha(p)) {
- out = put_replacement(out, q, in - 1 - q);
- flag = 2;
- } else {
- out = put_replacement(out, RE, strlen(RE));
- flag = 0;
- }
- }
- if (flag == 2 && !(isalpha(p) || isdigit(p))) {
- flag = 0;
- }
- *out++ = p;
- }
- if (flag == 1)
- out = put_replacement(out, RE, strlen(RE));
- *out++ = '\0';
- }
- int main(int argc, char *argv[])
- {
- const char *in = input;
- size_t outlen;
- char *out;
- /*
- * New length is counted as old * strlen(RE) / 2 + strlen(RE) since we
- * have to have delimiters. Additional strlen(RE) for the case, when
- * initial length is too small. And 1 for '\0' terminator.
- */
- outlen = strlen(in) * strlen(RE) / 2 + strlen(RE) + 1;
- out = malloc(outlen);
- if (!out)
- return ENOMEM;
- replace(in, out, outlen);
- printf("in: %s\n", in);
- printf("out: %s\n", out);
- free(out);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement