Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how cai i count the number of occur

Status
Not open for further replies.

5679

Programmer
Feb 14, 2003
32
AU
how cai i count the number of occurences of a substring in a larger string?
 
Here is a sample function:
Code:
int CountOcc(string s, string sub)
{
	int iCount = 0;
	int at =0;
	while (true)
	{
	int iPos = s.IndexOf(sub,at);
	if (iPos == -1)
		break;
		iCount++;
		at=iPos+sub.Length;
	}
	return iCount;
}
string s ="onetwo for onesixonetentwo one";
int count=CountOcc(s,"one"); // returns 4
-obislavu-
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top