File tree Expand file tree Collapse file tree 1 file changed +14
-5
lines changed Expand file tree Collapse file tree 1 file changed +14
-5
lines changed Original file line number Diff line number Diff line change @@ -693,12 +693,21 @@ void String::remove(unsigned int index){
693693}
694694
695695void String::remove (unsigned int index, unsigned int count){
696- if (index >= len) { return ; }
697- if (count <= 0 ) { return ; }
698- if (count > len - index) { count = len - index; }
699- char *writeTo = buffer + index;
696+ // removes characters from the middle of a string.
697+ if (count <= 0 ) { return ; } // exit if nothing to remove
698+ if (index >= len) { return ; } // ensure start is within string length; thus, ensures (len-index >= 1)
699+ if (count > len - index) { // ensure characters to remove is no larger than total length remaining
700+ count = len - index;
701+ }
702+ char *writeTo = buffer + index;
703+ char *copyFrom = buffer + index + count;
700704 len = len - count;
701- strncpy (writeTo, buffer + index + count,len - index);
705+
706+ // strncpy() cannot be used with overlapping buffers, so copy one char at a time
707+ unsigned int charactersToMove = len - index; // yes, uses post-adjusted length
708+ for (unsigned int i = 0 ; i < charactersToMove; i++, writeTo++, copyFrom++) {
709+ *writeTo = *copyFrom;
710+ }
702711 buffer[len] = 0 ;
703712}
704713
You can’t perform that action at this time.
0 commit comments