c语言:返回指定字符在指定字符串中第n次出现的位置(从0开始计算)

xiaoxiao2021-02-27  215

/*Function 返回指定字符在指定字符串中第n次出现的位置(从0开始计算)*/ /*函数原型 int myFunc(const char *s, char c, int n)*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int myFunc(const char *s, char c, int n) { #if 0 int flag = 0; int index = 0; if (NULL == s) { return -1; } while (*s != '\0') { if (*s == c) { ++flag; ++index; ++s; if (flag == n) { return index; } } ++s; ++index; } return index; #else / * * ****************************** 时间:2019/10/29 23:52:25 ************************** * 多谢读者[昨日红花今又开,似是故人来(https://me.csdn.net/weixin_43155866)]的提醒。 * 上面的代码有点问题,返回的地址下标本应该是从0开始计算的,结果是计算其个数,没有返回真实下标, * 现已对其重构逻辑并做优化。 */ assert(s); assert(n <= strlen(s)); int iNum = 0; const char *p = s; while(*p) { if(*p == c) { if(++iNum == n) break; else p++; } else p++; } return strlen(s)-strlen(p); #endif } int main() { char *str = "welcome to you"; int n =2; char ch = 'o'; int index = 0; index = myFunc(str,ch,n); printf("index = %d\n",index); system("pause"); return 0; }
转载请注明原文地址: https://www.6miu.com/read-15363.html

最新回复(0)