Count the occurrence of a specific character in a string by using substring in Scala -


i new programming. , i'm being asked count occurrence of specific character in string using substring , recursion in scala. totally lost , don't know how check equality of second character in string. not supposed use tailrecursion , map. many thanks!

my code far looks this:

def countchars(str:string, chr:char):int = {     if (str.length == 0)  0     else {     if (chr == str.substring(0,1)) 1     else 0}   + countchars() } println(countchars()) 

first of all, working version (haven't used shortest version make easier read):

def countchars(str: string, chr: char): int = {    if (str.length == 0) {      0    } else {      (if (chr.tostring() == str.substring(0, 1)) {         1      } else {         0      }) + countchars(str.substring(1), chr)    } }  println(countchars("hello world", 'l'))         //> 3 

you had 2 problems. first didn't call countchars right parameters. , more important , maybe not obvious: compared char string. never true:

chr == str.substring(0,1) 

because == or equals both checking type first, different. use typecast or in case simple tostring did.

hope helps you.

edit sorry pressed post button accidentily.


Comments

Popular posts from this blog

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

android - How to create dynamically Fragment pager adapter -

html - Outlook 2010 Anchor (url/address/link) -