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
...