about | help | code help+videos | done | prefs |
public boolean beginsHow(String str)
public boolean beginsHow(String str) { boolean begins = false; if (_____) { begins = true; } return begins; }Use the String method startsWith(String s) inside the parentheses: public boolean beginsHow(String str) { boolean begins = false; if ( str.startsWith("How") ) { begins = true; } return begins; }The method below uses the other version of startsWith(String s, int start), that has a 2nd parameter indicating at which position to start looking. public boolean beginsHow(String str) { boolean begins = false; if ( str.startsWith("How",0) ) { begins = true; } return begins; }In the code above, the 0 in startsWith() starts the search at the beginning of the string, with the 1st character. So startsWith("abc") and startsWith("abc",0) do the same thing. ________________________________ You can also start the search at other positions: 1 means start at the 2nd character 2 means start at the 3rd character public boolean beginsHowAtIndex1(String str) { boolean beginsAtPos1 = false; if ( str.startsWith("How", 1) ) { beginsAtPos1 = true; } return beginsAtPos1; }The method above will match strings like "xHow are you?" or "#How is that possible?" ________________________________ Note: you can also use an expression for where to start: int len = str.length(); int mid = str.length()/2; len-1 means start at the last character len-2 means start at the 2nd-to-last character len-3 means start at the 3rd-to-last character mid means start at the middle character* *If the string has an even length, there are two middle characters and mid is the position of the 2nd one. For example: str.startsWith("mm", mid) matches "recommend" str.startsWith("mm", mid-1) matches "summer" str.startsWith("ed", len-2) matches "trusted" [ an alternative to endsWith()! ] Finally, note that -- unlike with substring(int start, int stop), which has restrictions on the range of values for its start and stop parameters -- there are NO RESTRICTIONS on the range of values for the start parameter of startsWith(). That is, a negative nunber or one larger than the length of the string will NOT cause a runtime error. This internal error checking means that your programs can often be much easier to write using startsWith() than those that use combinations of length(), substring() and/or equals(). beginsHow("How are you?") → true beginsHow("how do you do?") → false beginsHow("Who are you?") → false ...Save, Compile, Run (ctrl-enter) |
Progress graphs:
Your progress graph for this problem
Random user progress graph for this problem
Random Epic Progress Graph
Difficulty: 1
Copyright Nick Parlante 2017 - privacy