Search code examples
c++cc-strings

Trimming start of Cstring without copying


I managed to get my homework to work but It shouldn't work because i have not finished it. I don't know why it does. I need help.

#include<iostream>
using namespace std;

char* trim(char* str) {
    const int lenStr = strlen(str);
    int characters = 0;
    bool trimmableFront = false;
    int firstChar;

    //check if trimmableFront + location of first char
    for (int i = 0; i < lenStr; i++) {
        if (*(str + i) != ' ') {
            if (characters == 0)
                firstChar = i;
            characters++;
        }
        if (characters == 0) {
            trimmableFront = true;
        }
    }

    //trim Front //THIS PART SHOULD BEHAVE DIFFERENTLY
    if (trimmableFront) {
        for (int i = 0; i < lenStr; i++) {
            if((firstChar + i <= lenStr))
                *(str + i) = *(str + firstChar + i); 
        }
    }
    return str;
}


int main() {

    char str[] = "       why does it work?";
    trim(str);
    cout<< str <<endl;
    return 0;
}

At the end of trim(*char) function, trimmed string should have still leftovers from previous locations. For some reason it is perfectly trimmed and works as intended printing "why does it work?" but it should print something like "why does it workt work?"


Solution

  • The reason why it works is because as you trim the string by shifting each character you also shift the terminating null character '\0'. As you probably know c-strings are array of characters terminated by '\0', so as you print str with cout all characters are printed until the null value is reached: that is way the leftovers are not printed.