查找一个指定字符在给定字符串中的出现的位置(和个数)

u014453825 2014-04-20 09:11:24
这个只能查找第一个字符额

求教如何能查询到给定字符在字符串中的所有位置,并计数额。。
#include<stdio.h>
#define SIZE 80
int main(void)
{
char s1[SIZE],ch;
int i,a;
printf("请输入一串字符串:");
gets(s1);
printf("输入待查找的字符:");
scanf("%c",&ch);
for(i=0;s1[i]!=ch&&i<SIZE;i++);
i=i+1;
if(i>SIZE)
i=0;
if(i>0)
printf("待查字符出现在字符串中的%d位置处\n",i);
else
printf("字符串中没有待查找的字符\n");
return 0;
}





谢谢
...全文
11899 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
阿_Sir 2014-04-21
  • 打赏
  • 举报
回复
//返回字符在字符串中出现的位置,如果没找到返回NULL int* findchar(char* str, char c, int& count) { if( str == NULL ) return NULL; count = 0; for(int i(0);str[i]!='\0';i++) { if( str[i] == c ) count++; } if( count<1 ) return NULL; int* pos = new int[count]; int index = 0; for(int i(0);str[i]!='\0';i++) { if( str[i] == c ) { pos[index] = i; index++; } } return pos; } int main() { int count; char _str[100]; char c; cout<<"请输入字符串:"<<endl; cin>>_str; cout<<"请输入待查找的字符:"<<endl; cin>>c; int* pos = findchar(_str,c,count); if( pos ) { cout<<"个数为:"<<count<<endl; cout<<"对应字符串的位置:"; for(int i(0);i<count;i++) cout<<pos[i]<<" "; cout<<endl; } else cout<<"没有找到对应字符"<<endl; 应该ok的,你试试吧
crazys_popcorn 2014-04-21
  • 打赏
  • 举报
回复
int num(char *p, char *p2, int *n)
{
	
	char *temp;    //临时指针用来做判断
	int k = strlen(p);//算出字符串Str的长度;也就是strinp的长度;
	while (p2 != '\0')   //如果到了那个比较长的字符串的末尾跳出循环
	{
		temp =strstr(p2, p);
		if(temp!= NULL)  //判断字符串STROUT。里面是否存在str  没有存放的话就等于null下面就直接跳出循环
		{
			(*n)++;     //调入进来的n++;
			p2 = p2 + strlen(p); 
			continue;
		}
		else         
		{
			break;  
		}
	}

}

int main()
{
	char strinp[] = "crazyspopcorn";  //定义一个字符型数组变量
	char strout[] = "crazyspopcornzuishuaiqilecrazyspopcornzuipiaole";
	int n = 0;
	num(strinp, strout, &n);
	printf("%d",n);
	system("pause");


}
头文件的话。楼主自家加哦~~这是调用函数的。楼主可以自己改写成一个函数的。希望能帮助到你;谢谢里面都有注释的。
lm_whales 2014-04-20
  • 打赏
  • 举报
回复
写个伪代码: for(每个字符位置){ 如果(发现 字符 ch) { 计数加一;输出数据位置; } 否则/** 没发现,**/ 什么也不做; } 输出计数;

70,020

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧