项目开发常见字符串处理模型-strstr-while/dowhile模型

---恢复内容开始---

strstr-whiledowhile模型用于在母字符串中查找符合特征的子字符串。

c语言库提供了strstr函数,strstr函数用于判断母字符串中是否包含子字符串,包含的话返回子字符串的位置指针,不包含的话返回NULL。

可以用strstr函数+while模型或者 strstr函数+dowhile模型实现:

1 strstr函数+while模型

#define _CRT_SECURE_NO_WARNINGS
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
  int ncount = 0;
  char *p = "abcd156445abcd456444abcd46844564abcd";
  while (p = strstr(p, "abcd"))//指针p指向a
  {
    ncount++;
    p = p + strlen("abcd");
    if (*p == '\0')
    {
      break;
    }
  }
  printf("字符串中出现abcd的次数: %d \n", ncount);  //运行可得4

  system("pause");
  return 0;
}

2 strstr函数+dowhile模型

#define _CRT_SECURE_NO_WARNINGS
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
  int ncount = 0;
  char *p = "abcd156445abcd456444abcd46844564abcd";
  do
  {
    p = strstr(p, "abcd");
    if (p != NULL)
    {
      ncount++;
      p = p + strlen("abcd");//找到abcd,指针继续往前
    }
    else
    {
      break;
    }
  } while (*p != '\0');
  printf("字符串中出现abcd的次数: %d \n", ncount);

  system("pause");
  return 0;
  }

封装查找子字符串出现次数的API:

#define _CRT_SECURE_NO_WARNINGS
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

int getCount(char*mystr, char*sub, int*ncount)
{
  bool ret = false;
  int tmpCount = 0;
  char*p = mystr;//记得函数中不要轻易改变形参的值

  //健壮代码
  if (mystr == NULL || sub == NULL)
  {
    ret = false;
    printf("fun getCount()err:%d (mystr == NULL || sub == NULL)\n", ret);
    return ret;
  }

  do
  {
    p = strstr(p, sub);
    if (p != NULL)
    {
      tmpCount++;
      p = p + strlen(sub); //指针达到下次查找的条件
    }
    else
    {
      break;
    }
  } while (*p != '\0');

  *ncount = tmpCount; //间接赋值是指针存在的最大意义
  ret = true;
  return ret;
}
int main()
{
  int count = 0;
  int ret = 0;
  char*p = "abcd156445abcd456444abcd46844564abcd";
  char *psub = "abcd";

  ret = getCount(p, psub, &count);
  if (ret <= 0)
  {
    printf("fun getCount()err:%d", ret);
  }
  printf("count:%d", count);
  system("pause");
  return 0;
}

猜你喜欢

转载自www.cnblogs.com/fengxing999/p/10264222.html