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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With