Linux_C第二次作业


第三天:
    1、自己实现 strstr 、 atoi 、 itoa 函数。
    2、输入一个整数,输出二进制1的个数。
        9  ---- >> 1001   --->  2  

    3、实现 strcmp 函数。

    4、实现一个函数,把字符串中的每个空格替换成“%20”。例如输入“we are happy”,输出为:“we%20are%20happy”

#include <stdio.h>
#include <string.h>
char *mystrstr(char *pa,char *pb)
{
    int i =strlen(pa);
    int j =strlen(pb);
    char *pc=NULL;
    while(*pa != '\0'){
        while(*pb ==  *pa){
            pb++;
            pa++;
            if (*pb == '\0'){
                pc = pa-j;
                return pc;
            }
        }
    pa++;
    }
    return pc;
}
int main(void)
{
    char *pb = "hello";
    char *pa = "world my hello like";    
    char *pc = mystrstr(pa,pb);
    printf("%s\n",pc);
    return 0;
}



#include <stdio.h>
void atoi(char *pc,int *pi)
{
	while(*pc != '\0'){
                *pi = (*pi)*10+ (*pc - '0');
                pc++;
        }
}
int main(void)
{
        char *pc = "00000123456";
        int tmp = 0;
	atoi(pc,&tmp);
        printf("%d\n",tmp);
        return 0;
}


#include <stdio.h>
void itoa(int tmp,char *pc)
{
	while(tmp != 0){
		*pc = '0' + tmp%10;
		tmp = tmp/10;
		pc++;
	}
}
int main(void)
{
	int tmp = 123456;
	char c[10] = "0";
	itoa(tmp,c);
	printf("%s\n",c);
	return 0;
} 



#include <stdio.h>
int count1 (int n)
{
	int num =0;
	if(n < 0){
		n = n*(-1);
		num++;
	}
	while(n>0){
		n = n&(n-1);
		num++;
	}
	return num;
}
int main(void)
{
	int i = -112;
	int num = count1(i);
	printf("%d\n",num);
	return 0;
}



#include <stdio.h>
#include <string.h>

int cmp(char* ps, char* pd)
{
	while(*ps != '\0' || *pd != '\0'){
		if(*ps > *pd )
			return 1;
		if(*ps < *pd)
			return -1;
		ps++;
		pd++;
	}
	return 0;
}
void bubble(char** pps, int len)
{
	char* tmp = NULL;
	int i, j;
	for(i=0; i<len; i++){
		for(j=0; j<len-i; j++){
			if(   (cmp( *(pps + j), *(pps + j + 1)))  > 0){
				tmp = *(pps + j);
				*(pps + j)  = *(pps + j + 1);
				*(pps + j + 1) = tmp;
			}
		}
	}
}
int main()
{
	char* ps[6] = {"hello", "world", "xian", "youdian", "ligong", "shannxi"};
	bubble(ps, 6);	
	int i = 0;
	for(i=0; i<6; i++)
		printf("%s\n", ps[i]);
	return 0;
}

#include <stdio.h>
void chargetonum (char *pa)
{
	char *pd = pa;
	int i =0;
	if(pa == '\0')
		return;
	while(*pd != '\0'){
		if(*pd == ' ')
			i++;
		pd++;
	}
	printf("i:%d\n",i);
	while(i){
		if(*pd !=' '){
			*(pd+2*i) = *pd;
		}
		else {
			*(pd+2*i-2)='%';
			*(pd+2*i-1)='2';
			*(pd+2*i)='0';
			i--;
		}
	pd--;
	}
}
int main(void)
{
	char c[20] = "we are happy";
	chargetonum(c);
	printf("%s\n",c);
	return 0;
}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值