随机产生一些字符,然后输入要查找的字符,本想将查找到的字符存储起来,要么初始化一个等大小的数组,要么要先检索出总共查找到多少个元素,再开辟空间存储,但这样相当于搜索了两遍,没有想到更好的方法,只是简单的将找到的字符打印出来。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 100
int getstr(char *str, int max)
{
int i;
srand(time(NULL));
for(i=0; i<max-1; i++)
{
if(rand()%2)
str[i] = rand() % 26 + 'A'; //产生在A-Z之间的字符
else
str[i] = rand() % 26 + 'a'; //产生在a-z之间的字符
putchar(str[i]);
}
str[max-1] = '\n';
putchar('\n');
return 0;
}
int search(char *str, char ch) //找出指定的字符并输出
{
//int pos[SIZE];
int count = 0;
int i = 0;
while(str[i] != '\n')
{
if(str[i] == ch)
{
//pos[count++] = i;
printf("str[%d]=%c\t",i, ch);
if(i%5 == 0)
putchar('\n');
count++;
}
i++;
}
printf("\n共有%d个%c。\n",count, ch);
return 0;
}
int main()
{
char str[SIZE];
char c;
char ch;
printf("输入要查找的字符:");
scanf("%c",&ch);
getstr(str, SIZE);
//while((c=getchar())!='\n' && (c=getchar())!=EOF);
search(str,ch);
return 0;
}