loading...

Daily Challenge #219 - Compare Strings

thepracticaldev profile image dev.to staff ・1 min read

Create a function called that accepts 2 string arguments and returns an integer of the count of occurrences the 2nd argument is found in the first one.

If no occurrences can be found, a count of 0 should be returned. The first argument can be an empty string. The second string argument must be of at least length 1.

Examples

strCount('Hello', 'o') // => 1
strCount('Hello', 'l') // => 2
strCount('', 'z') // => 0

Tests

strCount('oh goodness gracious', 'o')
strCount('howdy, pardner', 'd')
strCount('Incumbent President', 'e')

Good luck!


This challenge comes from shaddyjr on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Discussion

pic
Editor guide
Collapse
wobsoriano profile image
Robert

JavaScript

function strCount(text, letter) {
  if (!letter.length) {
    return 'a letter is required.';
  }

  return text.split('').filter(i => i === letter).length;
}

console.log(strCount('Hello world', '')) // a letter is required.
console.log(strCount('Hello world', 'l')) // 3
Collapse
empereol profile image
Empereol

TypeScript

/**
 * Return the number of occurances of the search character in the target string.
 *
 * @param target String to search.
 * @param search Character to search string for.
 *
 * @throws {Error} If search params is not exactly one character.
 *
 * @example
 * strCount('Hello', 'o') // => 1
 * strCount('Hello', 'l') // => 2
 * strCount('', 'z')      // => 0
 */
function strCount(target: string, search: string): number {
  if (!search || search.length !== 1) {
    throw new Error('Search character be exactly one character');
  }

  return (target.match(new RegExp(search, 'g')) || []).length;
}
Collapse
sabbin profile image
Sabin Pandelovitch

JS using a different approach, recursive function

The readable version

function strCompare(str, n, i = 0, c = 0) {
  const cond = str[i] === n ? c+1 : c;
  return i < str.length - 1 ? strCompare(str, n, i+1, cond) : cond;
}

One line version

const strCompare = (str, n, i = 0, c = 0) => (i < str.length - 1 ? strCompare(str, n, i+1, str[i] === n ? c+1 : c) : str[i] === n ? c+1 : c);
Collapse
aminnairi profile image
Amin

Actually, string[index out of bound] will return undefined so you don't need to check that your index is lower than the length of the string.

Also, you don't need to keep track of the characters' count if you just return it right in your recursive call.

And you can increment your index right when you access your character for comparison.

const strCount =
    (string, character, index = 0) =>
        string[index] === undefined
            ? 0
            : string[index++] === character
                ? 1 + strCount(string, character, index)
                : strCount(string, character, index);

If you are about the bytes, this makes it for a shorter version of your solution.

const count = (s, c, i = 0) => !s[i] ? 0 : s[i++] === c ? 1 + count(s, c, i) : count(s, c, i);
Collapse
sabbin profile image
Sabin Pandelovitch

You are right, thanks!

Collapse
gabriela profile image
Gabi

Java:
public static int strCount(String str, char letter) {
int count = 0;
for (char element : str.toCharArray()) {
if (element == letter) {
count++;
}
}
return count;
}

Collapse
olegthelilfix profile image
Oleg Aleksandrov
public static int strCount(String str, char letter) {
    return str.chars().filter(it -> it == letter).count();
}
Collapse
gabriela profile image
Gabi

Love it!

Collapse
lfrigodesouza profile image
Lucas Frigo de Souza

C#

public static int strCount(string text, char letter)
{
    var matches = Regex.Matches(text, $"{letter}");
    return matches.Count;
}

//Result
Console.WriteLine(strCount("Hello", 'o')); //1
Console.WriteLine(strCount("Hello", 'l')); //2
Console.WriteLine(strCount("", 'z')); //0
Console.WriteLine(strCount("oh goodness gracious", 'o')); //4
Console.WriteLine(strCount("howdy, pardner", 'd')); //2
Console.WriteLine(strCount("Incumbent President", 'e')); //3

Collapse
luffy_14 profile image
Ahmad Ra'fat

Python 3

def strCount(str1, str2):
    if not str1 or str2 not in str1:
        return 0

    return str1.count(str2)


def strCount_2(str1, str2):
    return str1.count(str2)

if __name__ == "__main__":
    print(strCount('Hello', 'o'))
    print(strCount('Hello', 'l'))
    print(strCount('', 'z'))

    print(strCount('oh goodness gracious', 'o'))
    print(strCount('howdy, pardner', 'd'))
    print(strCount('Incumbent President', 'e'))

Collapse
olegthelilfix profile image
Oleg Aleksandrov

Kotlin.

fun strCount(str1: String, str2: String): Int {
    var count = 0
    var matchIndex = 0
    var i = 0
    var indexOfFirstMatch = 0

    while (i < str1.length) {
        if (str1[i] == str2[matchIndex]) {
            if (matchIndex == 0) {
                indexOfFirstMatch = i
            }

            if ((++matchIndex) == str2.length) {
                count++
                matchIndex = 0
                i = indexOfFirstMatch + 1
            }
            else {
                i++
            }
        }
        else {
            i++
            matchIndex = 0
        }
    }

    return count
}

fun main() {
    println(strCount("Hello", "o"))
    println(strCount("Hello", "l"))
    println(strCount("", "z"))
    println(strCount("oh goodness gracious", "o"))
    println(strCount("howdy, pardner", "d"))
    println(strCount("Incumbent President", "e"))
 // also it's fine too
    println(strCount("Hello helllo", "ll"))
    println(strCount("eeeeeee", "ee"))
}
Collapse
vidit1999 profile image
Vidit Sarkar

Python one liner,

strCount = lambda str1, str2: len(str1) and len(str2) and str1.count(str2)

Output,

print(strCount('Hello', 'o')) # output -> 1
print(strCount('Hello', 'l')) # output -> 2
print(strCount('', 'z')) # output -> 0
print(strCount('oh goodness gracious', 'o')) # output -> 4
print(strCount('Hello', '')) # output -> 0
print(strCount('howdy, pardner', 'd')) # output -> 2
print(strCount('Incumbent President', 'e')) # output -> 3
print(strCount('', '')) # output -> 0
Collapse
kespri profile image
kespri

Swift solution :

func strCount(str: String, search: Character) -> Int {
    str.filter { $0 == search }.count
}

strCount(str:"Hello", search: "o") // => 1
strCount(str:"Hello", search: "l") // => 2
strCount(str:"", search: "z") // => 0
Collapse
fluffynuts profile image
Davyd McColl

JavaScript:

function strCount(haystack, needle) {
  return (
    (haystack || "")
      .match(new RegExp(`${needle}`, "g")) || []
  ).length;
}
Collapse
windeep profile image
windeep

Ruby

def str_count(text,letter)
  text.count(letter)
end