其他分享
首页 > 其他分享> > 统计某个字符串字符出现的次数,以及出现次数的最大值

统计某个字符串字符出现的次数,以及出现次数的最大值

作者:互联网

某字符串字符出现次数

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<p></p>

<body>
    <script>
        var pp = document.querySelector("p");
        var str = '123321asd1456&31413lkjh;loi33bui3';
        var s1 = new String();
        // 去重
        for (i = 0; i < str.length; i++) {
            //(s1.indexOf(str.[i]) == -1) 也可以
            if (s1.indexOf(str.charAt(i)) == -1) {
                s1 += str.charAt(i);
            }
        }
        console.log(s1);

        // s1中元素出现次数
        var max = 0;
        var zifu;
        for (i = 0; i < s1.length; i++) {
            var n = 0;
            for (j = 0; j < str.length; j++) {
                if (s1.charAt(i) == str.charAt(j)) {
                    n++;
                }
            }
            pp.innerHTML += s1.charAt(i) + "出现的次数是:" + n + "<br>";
            if (max < n) {
                max = n;
                zifu = s1.charAt(i);
            }
        }
        console.log(max, zifu);
        pp.innerHTML += "出现最多的字符是:" + zifu + "   出现次数是:" + max;
    </script>
</body>

</html>

标签:charAt,zifu,max,最大值,var,次数,str,字符串,s1
来源: https://blog.csdn.net/datuzidppd5556/article/details/99638730