There is the void TrimRight( char *s ) function, which has a very long s-style string as an argument. A passed string consists of a lot of white spaces after a last word and, also, throughout its length. It is required that the function is to trim excess white spaces at the right.
I suggested an implementation looking like this:
void TrimRight(char *str) {
char *space_pos{}; // last space position
auto iterator{str}; // string iterator
while (*iterator != '\0') {
if (*iterator == ' ') { // save first space
if (!space_pos) {
space_pos = iterator;
}
} else {
space_pos = nullptr;
}
++iterator;
}
if (space_pos) { // if the string does not end with alpha
*space_pos = '\0';
}
}
It works pretty well but N memory accesses seems excess, since the task given to me points out that a string is very long and contains many white spaces. Therefore, the question have been raised: Is there a way to refine the function in order to decrease a number of memory accesses?