查找指定字符串在另一字符串中的位置(strpos)
- #include "stdio.h"
- int main()
- {
- char* str = "linuxany.com";
- printf("pos1:%d\n",strpos(str,"any",1));
- printf("pos2:%d\n",strpos(str,"n",2));
- return 0;
- }
- //函数定义:取字符串位置,中文作为一个字符计算
- int strpos(const char* string,const char* find,int number)
- {
- char* pos = string;
- char* p = string;
- int count = 0;
- while (number > 0)
- {
- /*定义查找到的字符位置的指针,以便临时指针进行遍历*/
- pos = strstr(p,find);
- /*当位置指针为0时,说明没有找到这个字符*/
- if (pos == 0)
- return -1;
- /*当位置指针和临时指针相等说明下一个字符就是要找的字符,如果临时指针小于位置指针,则进行遍历字符串操作,并将count增1*/
- while(p <= pos)
- {
- if(*p > 0x80 || *p < 0)
- {
- p++;
- }
- p++;
- count++;
- }
- /*对要查找的次数减一*/
- number--;
- }
- return count;
- }
没有评论▼