patterncModerate
Function to erase a character in a string
Viewed 0 times
stringfunctioncharactererase
Problem
void chrrem (char arr[], size_t len, size_t pos)
{
memmove(arr + pos, arr + (pos + 1), (len - pos) + 1);
}It is supposed to be just fast.
Erases the character pointed by
pos (starting from 0)Note that this function works with a statically allocated array like so:
char arr [256] = "Mystring";
// >>
chrrem (arr, strlen(arr), 0);
chrrem (arr, strlen(arr), 0);
printf(arr);Output:
sringSolution
I am not a c programmer, and I know short, cryptic function and variable names are used in c for historical reasons, but I'll still comment that I don't like it one bit. I'd name the function
Given that the function is only intended to be used on c-strings, is the
Now we can actually justify the function wrapping the
Given the performance implications of moving memory like this, it might be a great idea to offer a companion function which allows the user to remove a range of characters.
I think it'd certainly be worthwhile to have a
And of course, it's important to be sure your code is well documented so that users are clear on exactly what they're getting with the function.
Also, this seems like a pretty easy thing to unit tests for, so be sure to do that.
removeCharacter.Given that the function is only intended to be used on c-strings, is the
len parameter actually necessary? Can't we eliminate that parameter and get the len in the same way your context code demonstrates calculating a c-string's length?void removeCharacter(char string[], size_t index) {
memmove(string+index, string + index + 1, strlen(string) - pos + 1);
}Now we can actually justify the function wrapping the
memmove. It makes it easier to use because all we have to do now is pass our string and the index of the character we want removed.Given the performance implications of moving memory like this, it might be a great idea to offer a companion function which allows the user to remove a range of characters.
void removeSubstring(char string[], size_t index, size_t length) {
memmove(string+index, string+index+length, strlen(string)-index+1);
}I think it'd certainly be worthwhile to have a
Range struct which has an index and length member, and simply pass this struct as the second argument instead of the index and length arguments.And of course, it's important to be sure your code is well documented so that users are clear on exactly what they're getting with the function.
Also, this seems like a pretty easy thing to unit tests for, so be sure to do that.
Code Snippets
void removeCharacter(char string[], size_t index) {
memmove(string+index, string + index + 1, strlen(string) - pos + 1);
}void removeSubstring(char string[], size_t index, size_t length) {
memmove(string+index, string+index+length, strlen(string)-index+1);
}Context
StackExchange Code Review Q#97061, answer score: 19
Revisions (0)
No revisions yet.