Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trimming spaces C++ POINTERS

I wrote simple function to trim spaces in text in function trim. It almost works. I have a problem because it should also change original string, but it doesn't. What is the problem? please describe. I appreciate any help. THANKS:) CODE:

#include <iostream>
#include <string.h>
using namespace std;

char* trim(char *str) {

    while(*str==' '){
        *str++;
    }

    char *newstr = str;

    return newstr; 
}


int main(){
    char str[] = "   Witaj cpp", *newstr;

    cout << "start" << str << "end" << endl;    // start   Witaj cppend

    newstr = trim(str);

    cout << "start" << str << "end" << endl;    // startWitaj cppend

    cout << "start" << newstr << "end" << endl;    // startWitaj cppend

    return 0;
}
like image 910
jawjaw Avatar asked Jun 06 '26 01:06

jawjaw


1 Answers

It shouldn't change the original string - even code like *str=something; doesn't apear. To modify the original string, you can write like this

char* trim(char *str) {
    char* oldstr = str;

    while(*str==' '){
        str++;//*str++; // What's the point of that *
    }


    char *str2 = oldstr;

    while(*str!='\0'){
        *(str2++) = *(str++);
    }
    *str2 = '\0';

    return oldstr;


}
like image 66
Wang Weiyi Avatar answered Jun 07 '26 19:06

Wang Weiyi