Count Occurrences Within a String

Home

Count the number of occurrences of a char or a substring within a String (both methods are provided, if you like you can use both in the same place at the same time).

	public static int countOccurrencesOf(String source, char pattern)
	{
		int count = 0;
		if (source!=null)
		{
			int found = -1;
			int start = 0;
			while( (found = source.indexOf(pattern, start) ) != -1) {
				start = found + 1;
				count++;
			}
			return count;
		}
		else return 0;
	}

	public static int countOccurrencesOf(String source, String pattern)
	{
		int count = 0;
		if (source!=null)
		{
			final int len = pattern.length();
			int found = -1;
			int start = 0;
			while( (found = source.indexOf(pattern, start) ) != -1) {
				start = found + len;
				count++;
			}
			return count;
		}
		else return 0;
	}