Still really new to programming and am using some exercises to understand the basics. This is my assignment:
Given a string, return a string made of the first 2 chars (if present), however include first char only if it is 'o' and include the second only if it is 'z', so "ozymandias" yields "oz". startOz("ozymandias") → "oz" startOz("bzoo") → "z" startOz("oxx") → "o"
I already had a look at the solution a do understand it, but can't figure out why my own attempt using substring instead of 'charAt generates a different output. Why does my own code1 using substring give a different output then when I would use 'charAt? Code1 is my own attempt, code2 is the given solution. In the attachments you will find the two outputs. Thank you!
//code 1 own attempt
public String startOz(String str) {
String answer = "";
if ( str.length() >= 1 && str.substring( 0 ).equals("o")) {
answer = answer + str.substring(0);
}
if ( str.length() >= 2 && str.substring( 1 ).equals("z")) {
answer = answer + str.substring(1);
}
return answer;
}
//code 2 the solution
public String startOz(String str) {
String answer = "";
if ( str.length() >= 1 && str.charAt( 0 ) == 'o') {
answer = answer + str.charAt(0);
}
if ( str.length() >= 2 && str.charAt( 1 ) == 'z') {
answer = answer + str.charAt(1);
}
return answer;
}
substring(int beginIndex)creates a substring frombeginIndex - string.lengthand doesn´t just return a single character atbeginIndex. You are rather looking forsubstring(int beginIndex, int endIndex).