-
AlgorithmsStrings
Description The hack has been banished.
Code /* Heap allocate the string and return it. */ char* remove_string(const char *input, const int n) { if (n <= 0 || input == NULL) return NULL; for (size_t i = 0, len = 0; i < (size_t)n; i++) { input += len; if ((len = strlen(input) + 1) == 1) return NULL; } return strdup(input); }
Test Cases char* remove_string(const char *input, const int n); void tester(const char *input, size_t index, const char *exp) { char *result = remove_string(input, index); if (exp == NULL) cr_assert_eq(result, NULL, "Expected NULL but got %s.", result); else cr_assert_str_eq(result, exp, "Expected '%s' but got '%s'.", exp, result); free(result); } Test(remove_string, should_pass_all_the_tests_provided) { tester("hello\0world\0", 1, "hello"); tester("well\0done\0", 2, "done"); tester("you\0are\0close\0", 3, "close"); tester("you\0almost\0finished\0the\0kumite\0", 5, "kumite"); tester("not\0the\0last\0string\0", 3, "last"); tester("edge\0case\0", 0, NULL); tester("another\0edge\0case\0", 4, NULL); }
Output:
-
Code - #include <stdlib.h>
- #include <string.h>
- /*
- Heap allocate the string and return it.
- */
- char* remove_string(const char *input, const int n)
- {
- if (n <= 0 || input == NULL) return NULL;
// This is a BIG hack, and I am unsure why it works since in an edge// situation where "n" is greater than the number of '\0' in the string,// the pointer will wander into unallocated memory.for (int c = 1; c < n; input++, (*input == '\0' ? c++ && input++ : c));char* res = strdup(input);return *res == NULL ? NULL : res;- for (size_t i = 0, len = 0; i < (size_t)n; i++)
- {
- input += len;
- if ((len = strlen(input) + 1) == 1) return NULL;
- }
- return strdup(input);
- }
- All
- {{group.name}} ({{group.count}})
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}