天天看點

截取字元串執行個體

#include <stdio.h>

//通過指針函數傳回一個截完的串的位址 
char *substring(char s[],int i,int j)
{
	//這個臨時數組必須是static,否則值傳不回去 
	static char temp[100];
	int n,m;
	for(m=0,n=i;n<=j;n++,m++)
	{
		temp[m]=s[n];
	}
	temp[m]='\0';
	return temp; 
} 

int main()
{
	char str[] = "I Love Programming";
	char *ps = NULL;
	ps = substring(str,2,5);
	printf("%s\n",ps);
	return 0; 
}           
//版本二 
#include <stdio.h>
 
char *substring(char s[],char temp[],int i,int j)
{	
	//static char temp[100];	//不再定義局部變量 
	int n,m;
	for(m=0,n=i;n<=j;n++,m++)
	{
		temp[m]=s[n];
	}
	temp[m]='\0';
	return temp; 
} 
 
int main()
{
	char str[] = "I Love Programming";
	char temp[100];		//定義一個存放截取字元串的數組 
	//截取串 
	substring(str,temp,2,5);
	printf("%s\n",temp);
	return 0; 
}           

繼續閱讀