随机产生100个字符(a~z)数组arrayOfChar,输入字符c,计算字符c在数组中出现的次数和位置。
#include <iostream>
using namespace std;
#include <time.h>
int main()
{
char arrayOfChar[100];
int randChar;
srand(time(NULL));
for (int i = 0; i < 100; i++)
{
randChar = rand() % 26;
arrayOfChar[i] = 'a' + randChar;
}
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
cout << arrayOfChar[i*10 + j] << " ";
cout << endl;
}
cout << endl;
while (1)
{
cout << "请输入单个字符:";
char enterChar;
cin >> enterChar;
int times = 0;
int earliest_index = -1;
int latest_index = -1;
for (int i = 0; i < 100; i++)
{
if (enterChar == arrayOfChar[i])
{
times++;
earliest_index = (-1 == earliest_index) ? i : earliest_index;
latest_index = i;
}
}
cout << "出现次数:" << times << endl;
cout << "最早出现索引:" << earliest_index << endl;
cout << "最后出现索引:" << latest_index << endl;
}
system("pause");
return 1;
}