Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,903 questions

51,834 answers

573 users

How to count the number of non-overlapping instances of substring in a string in C#

2 Answers

0 votes
using System;

public class CountNumberOfNonOverlappingInstancesOfSubstringInAString_CSharp
{
	public static int countOccurrences(string str, string substr) {
		if (substr.Length == 0) {
			return 0;
		}

		int count = 0;
		int offset = str.IndexOf(substr, StringComparison.Ordinal);
		while (offset != -1) {
			count++;
			offset = str.IndexOf(substr, offset + substr.Length, StringComparison.Ordinal);
		}

		return count;
	}

	public static void Main(string[] args)
	{
		string s = "java php c# c++ python php phphp";

		Console.WriteLine(countOccurrences(s, "php"));
	}
}

 
/*
run:
    
3
       
*/


 



answered Aug 24, 2024 by avibootz
0 votes
using System;

public class CountNumberOfNonOverlappingInstancesOfSubstringInAString_CSharp
{
	public static int countOccurrences(string str, string substr) {
		return (str.Length - str.Replace(substr, String.Empty).Length) / substr.Length;
	}

	public static void Main(string[] args)
	{
		string s = "java php c# c++ python php phphp";

		Console.WriteLine(countOccurrences(s, "php"));
	}
}

 
/*
run:
    
3
       
*/

 



answered Aug 24, 2024 by avibootz
...