C语言习题(1)——字符串拷贝,去空格,奇偶抽取字符串

本文介绍了三种实用的字符串操作方法:字符串拷贝、去除字符串首尾空格及抽取奇偶位置字符。通过具体示例展示了每种方法的实现过程及测试验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.字符串拷贝

/***
作者:一叶扁舟
作用:字符串的拷贝
时间:18:25 2017/5/1
***/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


int copyStr(char *from, char *to){
	if (from == NULL || to == NULL){
		return -1;
	}
	while (*from != '\0'){
		*to = *from;
		from++;
		to++;
	}
	*to = '\0';
	return 1;
}
int main(){
	char buf1[100];
	char buf2[100];
	strcpy(buf1, "abcdefgh");
	int temp = copyStr(buf1,buf2);
	if (temp != 1){
		printf("出错了!");
	}
	else{
	printf("%s", buf2);
	}

	printf("\n");
	system("pause");
	return 0;
}


2.字符串去除空格

/**
1、有一个字符串开头或结尾含有n个空格(”   abcdefgdddd    ”),欲去掉前后空格,返回一个新字符串。
要求1:请自己定义一个接口(函数),并实现功能;
要求2:编写测试用例。
int trimSpace(char *inbuf, char *outbuf);

**/
/***
作者:一叶扁舟
作用:
时间:19:55 2017/5/4
***/

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

int trimSpace2(char *inbuf, char *outbuf){
	char * result = outbuf;
	if (inbuf == NULL || outbuf == NULL){
		return -1;
	}
	while (*inbuf != '\0'){
		if (*inbuf == ' '){
			inbuf++;
		}
		else{
			*result = *inbuf;
			result++;
			inbuf++;
		}

	}

	*result = '\0';
	return 1;
}

void main(){
	char buff1[100] = "   abcdefgdddd    ";
	char buff2[100] = {0};
	trimSpace2(buff1,buff2);
	printf("%s",buff2);
	printf("\n");
	system("pause");

}




3.抽取奇偶字符串

/**
2、有一个字符串”1a2b3d4z”,;
要求写一个函数实现如下功能,
功能1:把偶数位字符挑选出来,组成一个字符串1
功能2:把奇数位字符挑选出来,组成一个字符串2
功能3:把字符串1和字符串2,通过函数参数,传送给main,并打印。
功能4:主函数能测试通过。
int getStr1Str2(char *souce, char *buf1, char *buf2);
*/

/***
作者:一叶扁舟
作用:
时间:20:28 2017/5/4
***/

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

int getStr1Str2(char *souce, char *buf1, char *buf2){
	if (souce == NULL || buf1 == NULL || buf2 == NULL){
		return -1;
	}
	char *p1 = buf1;
	char *p2 = buf2;

	int i = 1;
	while (*souce != '\0'){
		//偶数
		if (i % 2 == 0){
			*p1 = *souce;
			souce++;
			p1++;
		}else{//奇数
			*p2 = *souce;
			souce++;
			p2++;
		}
		i++;
	}

	return 1;
}

void main(){
	char buff1[100] = "a1b2c3d4e5f6g";
	char buff2[100] = { 0 };
	char buff3[100] = { 0 };
	int temp = getStr1Str2(&buff1, &buff2, &buff3);
	if (temp != -1){
		printf("偶数数据:\n%s\n", buff2);
		printf("奇数数据:\n%s\n", buff3);
	}
	else{
		printf("查取数据错误\n");
	}
	system("pause");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值