java script interview question challenge day 1.


Problem: Create a JavaScript function to count how many times a specific character appears in a given string. You must achieve this without using built-in methods like split() or match().

SOLUTION


  • We create an empty object charCount to store the count of each character.
  • We iterate through each character in the string.
  • For each character, we check if it already exists as a key in charCount. If it does, we increment its corresponding value by 1. If not, we initialize its value to 1.
  • Finally, we return the count of the target character from the charCount object. If the character doesn't exist in the string, we return 0.

This approach effectively uses the object as a hash map to count occurrences, providing a solution to the problem.

function countOccurrences(str, char) {
  
    const charMap = {};
    for (let i = 0; i < str.length; i++) {
        const currentChar = str[i];
        charMap[currentChar] = (charMap[currentChar] || 0) + 1;
    }
    return charMap[char] || 0;
}

const myString = "hello world";
const charToCount = "l";
console.log(countOccurrences(myString, charToCount));        

#JavaScript #StringManipulation #Hashmap #CountOccurrences #Algorithm #ProgrammingQuestion #CodingInterview #DataStructures

  • 该图片无替代文字

let abc = "hello world"; let x = 'o'; let y = 0; for (i = 0; i < abc.length; i++) { ?if (abc[i] === x) { ??y++ ?} } console.log(y)

要查看或添加评论,请登录

Sanjeev Kumar的更多文章

社区洞察

其他会员也浏览了