c++ trim 去字符串空格

来源:互联网 发布:ubuntu流量监控 编辑:程序博客网 时间:2024/04/26 02:48

现在麻烦的是每次用完需要free,其他方面都还行。

/*
Inputs:
src : 原始字符串
left: 去除左边的
right:去除右边的
all: 去除所有
return : dst chars
*/
char* trim_c(char* src, bool left = true, bool right = true, bool all = false){#ifndef SPACE_CHAR#define SPACE_CHAR ' '#define END_OF_CHAR '\0'#endifsize_t src_len = strlen(src);size_t h_ind = 0;//Trim all,very first priorityif (all){char* dst = (char*) malloc(src_len+1);int tink = 0;while(h_ind < src_len){if (src[h_ind] != SPACE_CHAR){dst[tink] = src[h_ind];tink++;}h_ind++;}dst[tink] = END_OF_CHAR;return dst;}//Trim leftif (left){while(src[h_ind] == SPACE_CHAR){h_ind++;}}//Trim rightif (right){while(src[src_len - 1] == SPACE_CHAR){src_len--;}}size_t new_len = (src_len - h_ind);char* buffer = (char*)malloc(new_len+1);memset(buffer, 0, new_len+1);memcpy(buffer, src+h_ind, new_len);buffer[new_len] = END_OF_CHAR;return buffer;}

原创粉丝点击