CSE116 Problem Set #1

advertisement
CSE116ProblemSet#1
ForeachofthefollowingproblemsyoushouldstartbywritingseveralJUnitteststhatwill
verifycorrectbehavior.Onceyouhavewrittenatleastfourdistincttestsforeachofthe
problems,begintoimplementsolutionstoeachoftheproblems.Besuretorunyourunit
testsoften.Forallthesemethods,whenitcomestimetoimplementthem,theonlymethods
youmaycallonaStringarecharAt(int)andlength().
1. Defineamethodnamedcount_ethatacceptsaStringasinputandreturnsthe
numberoftimesthechar‘e’occurs,asanint.
2. Defineamethodnamedcount_one_charthatacceptsaStringandacharasinputand
returnsthenumberoftimesthecharoccursintheString,asanint.
3. Defineamethodnamedcount_two_charsthatacceptsaStringandtwocharsas
input(i.e.ithasthreeparametersintotal).Assumingthatthetwocharparameters
arenamedcandd,definethismethodsothatitreturns,asanint,thenumberof
timesthecharcoccursintheinputaddedtothenumberoftimesthechardoccurs
intheinput.
4. Defineamethodnamedcount_chars_in_StringthatacceptstwoStringsasinput.
Assumingthatthetwoparametersarenamedsandcharacters,definethismethod
sothatitreturns,asanint,thenumberoftimesanyofthecharsinthesecondString
(characters)occurinthefirstString(s).
5. DefineamethodnamedisPalindromethatacceptsaStringasinputandreturns,asa
boolean,whethertheinputisapalindromeornot.Apalindromereadsthesame
wayforwardandbackwards.Rememberthatuppercaseandlowercasecharacters
aredistinct.
6. DefineamethodnamedhasAdjacentRepeatsthatacceptsaStringasinputand
returns,asaboolean,whethertheinputhastwoadjacentcharacterswhichare
identical.Forexample“book”has‘o’asanadjacentrepeat,whereas“oboe”does
not.
7. DefineamethodnamedfirstIndexOfAdjacentRepeatsthatacceptsaStringasinput
andreturns,asanint,thelowestindexatwhichtwo(ormore)adjacentcharacters
canbefoundintheinput,ifthereareadjacentrepeats.Otherwisethemethodmust
return-1.Fortheinput“book”theanswermustbe1.Fortheinput“oboe”the
answermustbe-1.
8. DefineamethodnamedreplaceVowelsthatacceptsaStringasinputandreturnsa
newStringwhichisjustliketheinputStringexceptthatallvowelshavebeen
replacedby‘*’.Forexample,forinput“book”thereturnedvaluemustbe“b**k”.
Assumethatthecharacters‘a’,‘e’,‘i’,‘o’and‘u’(andtheiruppercaseequivalents)are
vowels.
9. DefineamethodnamedreplaceCharactersthatacceptstwoStrings(calltheminput
andtargets)andachar(callitc)andreturnsanewStringidenticaltoinputexcept
thatanycharacterfromtargetsisreplacedbyc.Forexample,
replaceCharacters(“banana”,”bn”,’?’)mustreturn“?a?a?a”.
Download