找出字符串中子串的个数

编程入门 行业动态 更新时间:2024-10-25 01:23:00
本文介绍了找出字符串中子串的个数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我必须使用 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.

更多推荐

找出字符串中子串的个数

本文发布于:2023-10-19 14:55:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1507859.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中子   字符串   个数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!