找出字符串中子串的个数 [英] find the count of substring in string

查看:82
本文介绍了找出字符串中子串的个数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用 C 语言找到字符串中子字符串的数量.我正在使用函数 strstr 但它只找到第一个发生.

I have to find the count of a substring in a string using the C language. I'm using the function strstr but it only finds the first occurrence.

我对算法的想法类似于在字符串中搜索而 strstr 不返回 null 并且在每个循环中对主字符串进行子串.我的问题是如何做到这一点?

My idea of the algorithm is something like searching in the string while strstr does not return null and to substring the main string on each loop. My question is how to do that?

推荐答案

你可以这样做

int count = 0;
const char *tmp = myString;
while(tmp = strstr(tmp, string2find))
{
   count++;
   tmp++;
}

也就是说,当你得到结果时,在字符串的下一个位置再次开始搜索.

That is, when you get a result, start searching again at the next position of the string.

strstr() 不仅可以从字符串的开头开始,还可以从任何位置开始.

strstr() doesn't only work starting from the beginning of a string but from any position.

这篇关于找出字符串中子串的个数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆