Skip to content

2185. Counting Words With a Given Prefix #1108

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We can iterate through the words array and check if the given pref is a prefix of each word. You can use the substr function to check the beginning part of each string and compare it with pref. If they match, you increment the count.

Let's implement this solution in PHP: 2185. Counting Words With a Given Prefix

<?php
/**
 * @param String[] $words
 * @param String $pref
 * @return Integer
 */
function countWordsWithPrefix($words, $pref) {
    // Initialize count variable
    $count = 0;
    
    // Iterate through each word in the words array
    foreach ($words as $word) {
        // Check if the word starts with the prefix using substr
        if (substr($word, 0, strlen($pref)) === $pref)…

Replies: 1 comment 2 replies

Comment options

mah-shamim
Jan 9, 2025
Maintainer Author

You must be logged in to vote
2 replies
@topugit
Comment options

topugit Jan 9, 2025
Collaborator

@mah-shamim
Comment options

mah-shamim Jan 9, 2025
Maintainer Author

Answer selected by topugit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
2 participants