DEV Community

Daily Challenge #219 - Compare Strings

dev.to staff on April 06, 2020

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 ...
Collapse
 
sabbin profile image
Sabin Pandelovitch • • Edited

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
 
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
 
gabriel1 profile image
Gabriel •

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 • • Edited
public static int strCount(String str, char letter) {
    return str.chars().filter(it -> it == letter).count();
}
Collapse
 
gabriel1 profile image
Gabriel •

Love it!

Collapse
 
wobsoriano profile image
Robert • • Edited

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
 
kesprit profile image
kesprit •

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
 
olegthelilfix profile image
Oleg Aleksandrov • • Edited

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
 
lfrigodesouza profile image
Lucas Frigo de Souza • • Edited

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 • • Edited

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
 
sabbin profile image
Sabin Pandelovitch •

You are right, thanks!

Collapse
 
fluffynuts profile image
Davyd McColl • • Edited

JavaScript:

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