返回首页   进站必读

0822练习题


1.

有两个字符串(有效字符不超过9个)str1,str2,将str1,str2的对应字符按从小到大的顺序存放在一个数组的对应位置上,
如:str1 = “hello”;str2 = “akaedu”;
完成组合后,新的字符串为:“ahekaedllou”;1.c

/** 
* @file 1.c
* @brief 有两个字符串(有效字符不超过9个)str1,str2,将str1,str2的对应字符按从小到大的顺序存放在一个数组的对应位置上,
* 如:str1 = “hello”;str2 = “akaedu”;
* 完成组合后,新的字符串为:“ahekaedllou”;
* @author GuoPengyu
* @version 0.1
* @date 2011-09-09
*/
#include <stdio.h>

int main(int argc, char *argv[])
{
	char str1[] = "hello";
	char str2[] = "akaedu";
	char str[32] = {0};
	int i=0, j=0, k=0;

	while(str1[i] && str2[j])
	{
		if(str1[i] < str2[j])
			str[k++] = str1[i++];
		else
			str[k++] = str2[j++];
	}

	while(str1[i])
		str[k++] = str1[i++];
	while(str2[j])
		str[k++] = str2[j++];

	str[k] = '\0';
	
	printf("str1 = %s\nstr2 = %s\nafter...\nstr = %s\n", str1, str2, str);

	return 0;
}

2.

将两个字符串连接起来,并打印结果;
1)练习使用strcat()函数;(通过man手册或网络自学)
2)自己实现my_strcat();2.c

/** 
* @file 2.c
* @brief 将两个字符串连接起来,并打印结果; 
* 1)练习使用strcat()函数;(通过man手册或网络自学)
* 2)自己实现my_strcat()
* @author GuoPengyu
* @version 0.1
* @date 2011-09-09
*/
#include <stdio.h>
#include <string.h>

char *my_strcat(char *dest, const char *src)
{
	char *cp = dest;

	while (*cp)
		cp++;
	for (; (*cp = *src); cp++, src++)
		;

	return dest;
}


int main(int argc, char *argv[])
{
	const char src[16] = "akaedu";
	char dest[32] = "hello";

	//printf("after strcat src= %s\n", strcat(dest, src));
	printf("after my_strcat src= %s\n", my_strcat(dest, src));

	return 0;
}

3.

定义一个整形数组,用100以内的随机数填充,然后对其进行冒泡排序。
有关冒泡排序请查看这里3.c

/** 
* @file 3.c
* @brief 定义一个整形数组,用100以内的随机数填充,然后对其进行冒泡排序
* @author GuoPengyu
* @version 0.1
* @date 2011-09-09
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define LEN 10

int main(int argc, char *argv[])
{
	int i, j, tmp;	
	int num[LEN] = {0};

	srand(time(NULL));

	for(i = 0; i < LEN; i++)
	{
		num[i] = rand() % 100;	
		printf("%d, ", num[i]);
	}
	printf("\n");

	for(i = 0; i < LEN -1; i++)
	{
		for(j = 0; j < LEN -1 - i; j++)
		{
			if(num[j] > num[j+1])
			{
				tmp = num[j];
				num[j] = num[j+1];
				num[j+1] = tmp;
			}
		}
	}

	printf("after sort...\n");

	for(i = 0; i < LEN; i++)
	{
		printf("%d, ", num[i]);
	}
	printf("\n");

	return 0;
}