I am trying to implement substring in C. How efficient and standard is this code? I have a hard time understanding how C functions are usually meant to work, like how printf()
returns an int
or size_t
.
size_t substring(char *destination, char const *string, int start, int len) {
// writes a substring to the destinaton starting at start index of string until end stepping by step
// follows the same start at 0 off by one on the end format as Java substring method
int substringLength = len;
int stringLength = strlen(string);
if (start > stringLength || len > stringLength || start < 0 || len < 0) {
fputs("start and len must be 0 < start/len < length of string", stderr);
return -1;
}
if (start >= len) {
fputs("start must be start < len", stderr);
return -1;
}
memcpy(destination, &string[start], substringLength);
if (destination[stringLength] != '\x0') {
destination[stringLength] = '\x0';
}
return substringLength;
}
memmove()
ormemcpy()
to accomplish this. \$\endgroup\$memcpy()
. What's your point? \$\endgroup\$memmove()
ormemcpy()
directly, since those functions don't handle NUL-termination. \$\endgroup\$