473,763 Members | 5,396 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

count the number of occurrences of a substring in a string

Hi there,

Im trying to find the right way to code the loop to count the number of
occurences of a given substring in a string. Im able to find the first
occurence using the strstr function, but I just cant seem to think of
the right loop that would continue searching after finding this first
occurence. Could someone please help me out here?

Nov 15 '05 #1
4 14128

si*********@gma il.com wrote:
Hi there,

Im trying to find the right way to code the loop to count the number of
occurences of a given substring in a string. Im able to find the first
occurence using the strstr function, but I just cant seem to think of
the right loop that would continue searching after finding this first
occurence. Could someone please help me out here?


I think this is OK:

int
count_strinstr( const char *big, const char *little)
{
const char *p;
int count = 0;
size_t lil_len = strlen(little);

/* you decide what to do here */
if (lil_len == 0) return -1;

p = strstr(big, little);
while (p) {
count++;
p = strstr(p + lil_len, little);
}
return count;
}

If either arg is NULL this will probably barf.

-Charlie

Nov 15 '05 #2

"Charles Mills" <cm****@freeshe ll.org> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .

si*********@gma il.com wrote:
Hi there,

Im trying to find the right way to code the loop to count the number of
occurences of a given substring in a string. Im able to find the first
occurence using the strstr function, but I just cant seem to think of
the right loop that would continue searching after finding this first
occurence. Could someone please help me out here?


I think this is OK:

int
count_strinstr( const char *big, const char *little)
{
const char *p;
int count = 0;
size_t lil_len = strlen(little);

/* you decide what to do here */
if (lil_len == 0) return -1;

p = strstr(big, little);
while (p) {
count++;
p = strstr(p + lil_len, little);
}
return count;
}

If either arg is NULL this will probably barf.

-Charlie


It depends on whether the occurrences have to be distinctly separate from
one another.
Consider:
little is "abab"
big is "ababababababab "

Barry
Nov 15 '05 #3
Hey Charlie,

"p = strstr(p + lil_len, little);"

That addition of the string length was the logic that I was lookin for.
Thanks a lot for your help. Appreciate it.

Nov 15 '05 #4

<si*********@gm ail.com> wrote

"p = strstr(p + lil_len, little);"

That addition of the string length was the logic that I was lookin for.
Thanks a lot for your help. Appreciate it.

If you want to allow sustrings to overlap, add one to the pointer. If you
want to disallow this, add the length of the substring, as Charles showed
you.
Nov 15 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
7652
by: jester.dev | last post by:
Hello, I'm learning Python from Python Bible, and having some problems with this code below. When I run it, I get nothing. It should open the file poem.txt (which exists in the current directory) and count number of times any given word appears in the text. #!/usr/bin/python
1
4963
by: laredotornado | last post by:
Hello, I am trying to decipher an XSL sheet that is not my own, and yes, I'm a newbie. <xsl:template match="sentence"> <xsl:variable name="lines" select="count(line) + count(preceding::line)"/> <xsl:copy> <xsl:attribute name="sectionnumber"><xsl:value-of select="floor($lines div 15) + 1"/></xsl:attribute> <xsl:apply-templates/>
21
2513
by: rccf6178 | last post by:
Hi all, Do anyone know how to write a C program to count the frequency of a certain key pattern in a given datafile? Input: • Three alpha-numeric keys separated by space • A data file contains M by 3 matrix of alpha-numeric keys. Where M is number of rows and 3 is number of columns.
6
5072
by: dBNovice | last post by:
Hey group, I am trying to do a count of the number of papers in a table. The table has a PaperID that differentiates each paper , e.g. 004.1. Some papers are reused. The reused paper is given a new PaperID. The PaperID includes 3 new numbers appended to the original PaperID, e.g. 664.004.1. When I do a count, I do not want to count the reused paper. I set up a count query and had the criteria { Not Like "***.***.*" }. I have also
7
3478
by: Matteo Rattotti | last post by:
Hi all, i've noticed a strange beaviour of string.count: in my mind this code must work in this way: str = "a_a_a_a_" howmuch = str.count("_a_") print howmuch -> 3
2
2111
by: AtCor | last post by:
SELECT Sheet1$. AS , CASE Sheet1$. WHEN 'CSPP100A2344' THEN '0' END AS Extension, SUBSTRING(Sheet1$., 1, 4) AS , SUBSTRING(Sheet1$., 5, 8) AS , SUBSTRING(Sheet1$., 1, 4) + '_' + SUBSTRING(Sheet1$., 5, 8) AS , Sheet1$. + '_' + SUBSTRING(Sheet1$., 1, 4) + '_' + SUBSTRING(Sheet1$., 5, 8) AS , Sheet1$. + Sheet1$.Surname AS , CASE Sheet1$.NOTES WHEN 'visit...
9
2036
by: nick048 | last post by:
Hi to All, I need to search the string occurencies in a structure like this: struct node { char info; struct node *next; };
3
4947
by: Beeteh | last post by:
Hello everybody! I'm a so-called newbie at programming in C/C++ and I'm currently working on a poject that searches for a particular string in a file. The user enters the string he/she is searching for, and the program is supposed to return the number of occurrences of the string in the file along with the line numbers at which the string occurs, or an error message saying string not found. I've managed to write the code for searching for...
26
2455
by: Ping | last post by:
Hi, I'm wondering if it is useful to extend the count() method of a list to accept a callable object? What it does should be quite intuitive: count the number of items that the callable returns True or anything logically equivalent (non-empty sequence, non-zero number, etc). This would return the same result as len(filter(a_callable, a_list)), but without constructing an intermediate list which is thrown away after len() is done.
0
9387
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10148
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10002
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9938
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8822
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6643
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2794
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.