這個模型也很簡單,參數里面一個是方法計算非空串個數,一個是返回非空串的內容。
主要還是接口的封裝設計,要調用函數獲得內容,就要把接口設計成一級指針的形式。除此之外,還要注意是參數是在主調函數里面分配內存。
int trimSpaceStr(char * p,char* buf,int * mycount){
int ret = 0;
int count = 0 ;
int i, j;
//設定起始指針位置
i = 0;
//設定末端指針位置
j = strlen(p) - 1;
while (isspace(p[i]) && p[i] != '\0') {
i++;
}
while (isspace(p[j])&& j > 0) {
j--;
}
count = j - i + 1;
//這里其實主要要注意的是這個函數
strncpy(buf, p+i, count);
buf[count] = '\0';
*mycount = count;
return ret;
}
int main(int argc, const char * argv[]) {
char buf[] = " abcd ";
char buf2[1024] = {0};
int count = 0;
trimSpaceStr(buf, buf2,&count);
printf("buf2:%s \n",buf2);
printf("count:%d \n",count);
system("pause");
return 0;
}
另外有一個特別要注意的點是
char buf[] = " abcd ";
char *p = " abcd ";
buf和p中指向的字符串并不是同一個區域,buf指向的是stack中的區域,而p是指向常量區的,我們可以修改buf中的內容,但是并不能改變p指向常量區中的內容。