如何计算字符串中特定字符的出现 [英] How to count the occurrence of a specific character in a string

查看:72
本文介绍了如何计算字符串中特定字符的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定从哪里开始检查n次出现的特定字符的字符串.我已经列出了我认为是该函数框架的基本轮廓,但是我不确定的内容是什么?

I'm not sure where to begin with the checking of a string for n occurrences of a specific char. I've laid out the basic outline of what I assume to be the framework for the function but the contents I'm not sure about?

let countCharFromNth (getStr : string)(chkdChar : char) = 
    if getStr.Length >=1 then 

    else printfn "Not enough arguments"

推荐答案

这是尾部递归循环版本.

Here is a tail recursive loop version.

let countCharFromNth (getStr : string)(chkdChar : char) = 
    let rec loop i count =
        if i < getStr.Length then 
            if getStr.[i] = chkdChar then loop (i+1) (count+1)
            else loop (i+1) count
        else count
    loop 0 0

由于所有函数调用都位于尾部(最后)位置,因此编译器会将其转换为命令式循环.虽然比其他版本更长,但这是最有效的方式,因为它不会创建不必要的中间集合.

It will get translated into an imperative loop by the compiler as all function calls are in the tail (last) position. While longer than the other versions, this is the most performant way of doing it as it does not create unnecessary intermediate collections.

这篇关于如何计算字符串中特定字符的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆