1、从键盘输入一串字符以及一个字符,找到这个字符在字符串中出现的第一次的位置和最后一次的位置的间距是多少。
输入:abcdefdefd输出:字符d
第一次出现在第4个最后一次出现在第7个第一次的位置和最后一次的位置间距为:3
分别从首尾两个方向搜索这个字符,第一个找到的两个位置就是了
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char s[100],ch;
gets(s);
ch = getchar();
int pos1=-1,pos2=-1;
int n = strlen(s);
for(int i=0;i<n;i++)
if(s[i] == ch)
{
pos1 = i;
break;
}
for(int i=n-1;i>=0;i--)
if(s[i] == ch)
{
pos2 = i;
break;
}
if(pos1 >= 0 && pos2>=0)
cout<<pos2-pos1<<endl;
else
cout<<"字符没有出现两次"<<endl;
return 0;
}
运行结果:
代码如下:
#include <iostream>
using namespace std;
int main()
{
char buf[100];
int i=0;
int start=-1,end =0;
char ch;
cin.getline(buf,100);
cin >> ch;
while(buf[i])
{
if(buf[i] == ch)
{
if(start == -1)
start = i;
else
end = i;
}
i++;
}
cout <<"第一次出现在第" << start+1<<"个,最后一次出现在第"<<end+1<<"个,第一次的位置和最后一次的位置间距为:"<< end-start<<endl;
return 0;
}