substr_count

substr_count(string $haystack, string $needle, int $offset = 0, ?int $length = null): int

Counts how many times a substring occurs in a string (non-overlapping), with an optional offset/length window.

C C23

C23
#include <stdio.h>
#include <string.h>

/* Hand-written strstr loop: jump past the whole hit → no overlapping counts; offset/length emulated with pointers + truncation */
static int substr_count(const char *haystack, size_t offset, size_t length, const char *needle) {
    char buf[64];
    size_t n = strlen(haystack);
    if (offset > n) return 0;
    if (length > n - offset) length = n - offset;
    memcpy(buf, haystack + offset, length);
    buf[length] = '\0';
    int count = 0;
    const char *p = strstr(buf, needle);
    while (p != NULL) {
        count++;
        p = strstr(p + strlen(needle), needle); /* Continue from the hit's end → no overlapping counts */
    }
    return count;
}

int main(void) {
    printf("%d\n", substr_count("hello world hello", 0, 64, "hello")); /* 2 */
    printf("%d\n", substr_count("aaaa", 0, 64, "aa"));      /* 2: no overlapping counts */
    printf("%d\n", substr_count("abcabcabc", 3, 64, "abc")); /* from offset 3 → 2 */
    printf("%d\n", substr_count("abcabcabc", 0, 6, "abc"));  /* first 6 bytes only → 2 */
    return 0;
}
Output
2
2
2
2

C++ C++26

C++26
#include <iostream>
#include <string>

// Hand-written find loop: jump past the whole hit → no overlapping counts; offset/length emulated with substr
static int substr_count(const std::string &haystack, size_t offset, size_t length, const std::string &needle) {
    std::string region = haystack.substr(offset, length);
    int count = 0;
    for (size_t pos = region.find(needle); pos != std::string::npos;
         pos = region.find(needle, pos + needle.size())) {
        count++;
    }
    return count;
}

int main() {
    std::cout << substr_count("hello world hello", 0, 64, "hello") << "\n"; // 2
    std::cout << substr_count("aaaa", 0, 64, "aa") << "\n";      // 2: no overlapping counts
    std::cout << substr_count("abcabcabc", 3, 64, "abc") << "\n"; // from offset 3 → 2
    std::cout << substr_count("abcabcabc", 0, 6, "abc") << "\n";  // first 6 bytes only → 2
    return 0;
}
Output
2
2
2
2

C# v11.0.100

v11.0.100
// No built-in count: hand-written IndexOf loop (jump past the whole hit → no overlapping counts); offset/length emulated with ranges
static int SubstrCount(string haystack, string needle, int offset, int length)
{
    int end = (int)Math.Min((long)offset + length, haystack.Length);
    string region = haystack[offset..end];
    int count = 0, pos = region.IndexOf(needle, StringComparison.Ordinal);
    while (pos != -1)
    {
        count++;
        pos = region.IndexOf(needle, pos + needle.Length, StringComparison.Ordinal);
    }
    return count;
}

Console.WriteLine(SubstrCount("hello world hello", "hello", 0, int.MaxValue)); // 2
Console.WriteLine(SubstrCount("aaaa", "aa", 0, int.MaxValue)); // 2: no overlapping counts
Console.WriteLine(SubstrCount("abcabcabc", "abc", 3, int.MaxValue)); // from offset 3 → 2
Console.WriteLine(SubstrCount("abcabcabc", "abc", 0, 6)); // first 6 characters only → 2
Output
2
2
2
2

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"strings"
)

func main() {
	// strings.Count semantics match substr_count — non-overlapping counting; offset/length emulated with slices
	fmt.Println(strings.Count("hello world hello", "hello")) // 2
	fmt.Println(strings.Count("aaaa", "aa"))                 // 2: no overlapping counts
	fmt.Println(strings.Count("abcabcabc"[3:], "abc"))       // from offset 3 → 2
	fmt.Println(strings.Count("abcabcabc"[:6], "abc"))       // first 6 bytes only → 2
}
Output
2
2
2
2

Java v27.0.1

v27.0.1
public class Main {
    // No built-in count: hand-written indexOf loop (jump past the whole hit → no overlapping counts); offset/length emulated with a window
    static int substrCount(String haystack, String needle, int offset, int length) {
        int end = (int) Math.min((long) offset + length, haystack.length());
        String region = haystack.substring(offset, end);
        int count = 0, pos = region.indexOf(needle);
        while (pos != -1) {
            count++;
            pos = region.indexOf(needle, pos + needle.length());
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(substrCount("hello world hello", "hello", 0, Integer.MAX_VALUE)); // 2
        System.out.println(substrCount("aaaa", "aa", 0, Integer.MAX_VALUE)); // 2: no overlapping counts
        System.out.println(substrCount("abcabcabc", "abc", 3, Integer.MAX_VALUE)); // from offset 3 → 2
        System.out.println(substrCount("abcabcabc", "abc", 0, 6)); // first 6 characters only → 2
    }
}
Output
2
2
2
2

JavaScript v26.13.1

v26.13.1
// No built-in count: hand-written indexOf loop (continue from the hit's end → no overlapping counts); slice auto-clamps the tail
function substrCount(haystack, needle, offset = 0, length = Infinity) {
  const region = haystack.slice(offset, offset + length);
  let count = 0, pos = region.indexOf(needle);
  while (pos !== -1) {
    count++;
    pos = region.indexOf(needle, pos + needle.length); // Jump past the whole hit → no overlapping counts
  }
  return count;
}
console.log(substrCount("hello world hello", "hello")); // 2
console.log(substrCount("aaaa", "aa")); // 2: no overlapping counts
console.log(substrCount("abcabcabc", "abc", 3)); // from offset 3 → 2
console.log(substrCount("abcabcabc", "abc", 0, 6)); // first 6 characters only → 2
Output
2
2
2
2

PHP v8.6.0

v8.6.0
// substr_count: built-in substring counting — **no overlapping counts** (the tally companion of the strpos family)
echo substr_count("hello world hello", "hello"), "\n"; // 2
echo substr_count("aaaa", "aa"), "\n";                 // 2: positions 0/2, the overlapping position 1 not counted
echo substr_count("abcabcabc", "abc", 3), "\n";        // starting at offset 3 → 2
echo substr_count("abcabcabc", "abc", 0, 6), "\n";     // first 6 bytes only → 2
Output
2
2
2
2

Python v3.15.2

v3.15.2
# str.count semantics match substr_count — non-overlapping; start/end map natively to offset/length
print("hello world hello".count("hello"))  # 2
print("aaaa".count("aa"))                  # 2: Python does not count overlaps either
print("abcabcabc".count("abc", 3))         # start at 3 → 2
print("abcabcabc".count("abc", 0, 6))      # first 6 characters only → 2
Output
2
2
2
2

Rust v1.99.1

v1.99.1
fn main() {
    // The str::matches iterator is naturally non-overlapping; offset/length emulated with slices
    println!("{}", "hello world hello".matches("hello").count()); // 2
    println!("{}", "aaaa".matches("aa").count());                 // 2: no overlapping counts
    println!("{}", "abcabcabc"[3..].matches("abc").count());      // from offset 3 → 2
    println!("{}", "abcabcabc"[..6].matches("abc").count());      // first 6 bytes only → 2
}
Output
2
2
2
2

TypeScript v26.13.1

v26.13.1
// No built-in count: hand-written indexOf loop (continue from the hit's end → no overlapping counts); slice auto-clamps the tail
function substrCount(haystack: string, needle: string, offset = 0, length = Infinity): number {
  const region = haystack.slice(offset, offset + length);
  let count = 0, pos = region.indexOf(needle);
  while (pos !== -1) {
    count++;
    pos = region.indexOf(needle, pos + needle.length); // Jump past the whole hit → no overlapping counts
  }
  return count;
}
console.log(substrCount("hello world hello", "hello")); // 2
console.log(substrCount("aaaa", "aa")); // 2: no overlapping counts
console.log(substrCount("abcabcabc", "abc", 3)); // from offset 3 → 2
console.log(substrCount("abcabcabc", "abc", 0, 6)); // first 6 characters only → 2
Output
2
2
2
2

Language differences

Overlap semantics are this entry's core: every language counts non-overlapping — substr_count("aaaa","aa") is 2, not 3; overlapping counting needs a hand-written loop (+1 per position, advance by 1).

C: no built-in — a hand-written strstr loop (example); the key is resuming from the match's end (p + strlen(needle)).

C++: same idea with a string::find loop (example); ranges offer no ready-made count.

C#: no built-in count — a hand-written IndexOf loop (example); LINQ has nothing either.

Go: strings.Count matches PHP's semantics (non-overlapping); offset/length become slices s[3:]/s[:6].

Java: no built-in count — a hand-written indexOf loop (example); Apache Commons Lang's StringUtils.countMatches is also non-overlapping.

JavaScript: no built-in — a hand-written indexOf loop (example); regex global matching s.match(/aa/g)?.length is naturally non-overlapping too.

PHP: substr_count is built in — $offset/$length slice the counting window directly (out of range gives false/warnings); non-overlapping; pairs with the strpos family (strpos/strrpos/stripos).

Python: str.count matches PHP's semantics (non-overlapping) and its start/end parameters natively correspond to offset/length — the lowest migration cost of the ten.

Rust: str::matches().count() is naturally non-overlapping; offset/length become slices s[3..]/s[..6] (out of range panics — check bounds yourself).

TypeScript: same as JavaScript (hand-written loop or regex global matching).