0

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;
}

output code1

//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;
}

output code2

1
  • 2
    Because substring(int beginIndex) creates a substring from beginIndex - string.length and doesn´t just return a single character at beginIndex. You are rather looking for substring(int beginIndex, int endIndex). Commented Oct 23, 2015 at 8:36

2 Answers 2

1

Here is documentation for substring(int index)

public String substring(int beginIndex)

Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

So for first if you get ozymandias and it is not equal to o. Correct would be to use:

substring(int beginIndex, int endIndex)

Documentation:

public String substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is

endIndex-beginIndex.

Link: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring%28int%29

Sign up to request clarification or add additional context in comments.

Comments

0

Read the javadocs on String#substring - you need to add an extra parameter specifying the end of the substring, else it returns the rest of the string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.