标签:style blog ar color sp for div log bs
思路:
源代码如下:
void stripSpace(char str[],int length) { if(str==NULL) return; char *temp = str; int last = length-1; int space_count_head = 0; int space_count_tail = 0; while(*temp==‘ ‘) { space_count_head++; temp++; } while(str[last]==‘ ‘) { space_count_tail++; last--; } int length_new = length-space_count_head-space_count_tail; int len = length_new; char *ret = str; while(length_new>0) { *str++= *temp++; length_new--; } ret[len]=‘\0‘; }
main函数如下所示:
int main() { char str[] = " hello world "; char *p = str; cout << "before strip:" << endl; cout << "str is " << endl; cout << str << endl; cout << "before: strlen(str) " << strlen(str) << endl; int length = strlen(str); stripSpace(str,length); cout << "after strip:" << endl; cout << "str is " << endl; cout << str << endl; cout << "after: strlen(str) " << strlen(str) << endl; return 0; }
开始我将原始字符串定义为:char *str = " hello world ",发现str在被调用函数中不能进行原址修改,如 str[1] = ‘d‘是不允许的。
另外一个调了很久的bug就是在最后加‘\0‘时直接加在了str上,str[len]=‘\0‘,实际上str的位置在进行原址拷贝的时候已经变动,这时会产生野指针,所以应该记下str的起始位置。
标签:style blog ar color sp for div log bs
原文地址:http://www.cnblogs.com/hubavyn/p/4145224.html