返回首页   进站必读

0829练习题


1.

找9问题:从1到100中找出有多少个9; 要求:设计函数实现;函数不仅可以找9,还可以找8,找7…;
1.c

/** 
* @file 1.c
* @brief 找9问题:从1到100中找出有多少个9;
* 要求:设计函数实现;函数不仅可以找9,还可以找8,找7…
* @author Gaojinlong
* @version 0.1
* @date 2011-09-09
*/

#include <stdio.h>

int find_x(int num, int x)
{
        int count = 0;

        do{
                if(num % 10 == x)
                        count++;
        }while(num /= 10);

        return count;
}

int main(int argc, const char *argv[])
{
        int count = 0, i;
        int x;

        printf("num to find: ");
        scanf("%d", &x);
        for(i = 1; i <= 100; i++)
        {
                count += find_x(i, x);
        }
        printf("%d\n", count);

        return 0;
}

2.

从键盘接收一个字符串,然后按照字符顺序从小到大进行排序并删除重复字符; 如从键盘输入的内容为”agehiagehp”,执行完程序之后变成:”aeghip”;
2.c

/** 
* @file 2.c
* @brief 从键盘接收一个字符串,然后按照字符顺序从小到大进行排序并删除重复字符;
* 如从键盘输入的内容为”agehiagehp”,执行完程序之后变成:”aeghip”
* @author GuoPengyu
* @version 0.1
* @date 2011-09-09
*/
#include <stdio.h>
#include <string.h>

#define N 32

void sort(char *str)
{
	int i, j, pos, len;
	char tmp;

	len = strlen(str);
	for(i = 0; i < len - 1; i++)
	{
		pos = i;
		for(j = i+1; j < len; j++)
		{
			if(str[pos] > str[j])
				pos = j;
		}
		if(pos != i)
		{
			tmp = str[i];
			str[i] = str[pos];
			str[pos] = tmp;
		}

	}
}

void del(char *str)
{
	int i, j, k;

	for(i=1, k=1; str[i] != '\0'; i++)
	{
		for(j = k-1; j >= 0; j--)
		{
			if(str[i] == str[j])
				break;
		}
		if(j < 0)
			str[k++] = str[i];
	}
	str[k] = '\0';
}

int main(int argc, char *argv[])
{
	char str[N] = "jsajglksdfl";

	printf("str = %s\n", str);
	sort(str);
	printf("after sort\nstr = %s\n", str);
	del(str);
	printf("after del\nstr = %s\n", str);

	return 0;
}

3.

删除字符串中的子字符串;
3.c

/** 
* @file 3.c
* @brief 删除字符串中的子字符串
* @author Gaojinlong
* @version 0.1
* @date 2011-09-09
*/
#include <stdio.h>
#include <string.h>

#define N 128

void del(char *str, char *substr)
{
        char *p;

        int len_sub = strlen(substr);
        while(p = strstr(str, substr))
        {
                *p = '\0';
                strcat(str, p + len_sub);
        }
}

int main(int argc, char *argv[])
{
	char str[N] = "helllo akaedullo";
	char sub[N] = "llo";

	printf("str = %s\n", str);
	del(str, sub);
	printf("After...\nstr = %s\n", str);

	return 0;
}