Substring in c programming

在c++中,string類型的變量有substr方法用來取字串,現實現c中的字符串char *的取字串方法,代碼:

char *substring(char *str,int pos,int len){
	char *pointer;
	int c;
	pointer=(char *)malloc(len+1);
	if(pointer==NULL){
		printf("unable to allocate memory.\n");
		exit(EXIT_FAILURE);
	}
	for(int i=0;i<pos;i++){
		str++;
	}
	for(int i=0;i<len;i++){
		*(pointer+i)=*str;
		str++;
	}
	*(pointer+len)='\0';
	return pointer;
}
注意:返回指針類型,那麼在函數體內聲明的變量是局部變量,函數執行結束後,變量的地址空間被自動收回,所以要使用malloc函數申請動態空間,執行後要判斷是否申請成功。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章