logo CodeStepByStep logo

sameDashes

Language/Type: Java string parameters return boolean
Related Links:

Write a method named sameDashes that accepts two strings as parameters and that returns a boolean value indicating whether or not they have dashes in the same places (returning true if they do and false if not). For example, below are four pairs of strings of equal length that have the same pattern of dashes. Notice that the last pair has no dashes at all.

  • string 1:    "hi--there-you."        "-15-389"        "criminal-plan"        "abc"
  • string 2:    "12--(134)-7539"        "-xy-zzy"        "(206)555-1384"        "9.8"

So a call of sameDashes("hi--there-you.", "12--(134)-7539") should return true. By contrast, the call of sameDashes("hi--there-you", "hey-there-yo-") should return false because the first string has an unmatched dash at index 2 and the second string has an unmatched dash at index 12.

To be considered a match, the strings must have exactly the same number of dashes in exactly the same positions. Note that the strings might be of different length, but different-length strings might still return true if it turns out that all of their dashes are in the range of indexes that is within the bounds of the shorter string. For example, the following calls should each return true, because the strings each have two dashes and they are in the same positions.

sameDashes("1st-has-more characters", "2nd-has-less")
sameDashes("1st-has-less", "2nd-has-more chars")

But the following should return false because the longer string has a third dash where the shorter does not:

sameDashes("1st-has-more-chars", "2nd-has-less")
sameDashes("1st-has-less", "2nd-has-more-characters")

Constraints: You should not use any data structures such as arrays to help you solve this problem. But you can declare as many simple variables like int, char, etc. as you like. Declaring auxiliary String variables is also fine.

Type your Java solution code here:


This is a method exercise. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.

Log In

Need help?

If you do not understand how to solve an exercise or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect tests, etc.), please

Is there a problem? Contact a site administrator.

©, all rights reserved.