1

I stumbled upon the following problem:

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".

Bellow is my try, but please take in consideration that I am a begginer.

public String startOz(String str) {
 if(str.length()>=2 && str.substring(0,2)=="oz")
     return "oz";
 if(str.length()>=1 && str.substring(0,1)=="o")
     return "o";
 if(str.length()>=2 && str.substring(1,2)=="z")
     return "z";
   return "";
}   

Unfortunately this code doesn't include all the possibilities, maybe is better understandable with an example, if the input would be: startOz("ozk") then instead of "oz" the output will be just a blank space.. Is there a way to salvage my attempt?

  • 2
    Well first of all don't compare `Strings` with `==`, use `.equals()`: `str.substring(0,2).equals("oz")` – GBlodgett Dec 20 '18 at 00:09
  • Wow, thank you! It works perfectly now. But why isn't "==" working for Strings? –  Dec 20 '18 at 00:13
  • @Dahaka please give more test conditions. I am not able to completely figure out expected output. Please give more input with their expected output – Brij Raj Kishore Dec 20 '18 at 00:16
  • 1
    @Dahaka Please read the proposed duplicate question.. It explains in great detail – GBlodgett Dec 20 '18 at 00:18
  • @GBlodgett I don't know if it's duplicate or not, but these answers helped me alot! Also, how do you write comments in code mode? –  Dec 20 '18 at 01:18
  • 1
    @Dahaka What do you mean in code mode? Like `this`? (If so use the ` symbol before and after the part you want to highlight. ` like this `, except without the spaces) – GBlodgett Dec 20 '18 at 03:30

5 Answers5

3

You could just check the position of the characters and see if they're correct. Like this

String str = ("ozymondiaz");    
String returnString = ("");
if(str.length()>1 && str.charAt(0) == 'o') { returnString+=("o"); } 
if(str.length()>2 && str.charAt(1) == 'z') { returnString+=("z"); } 
    System.out.print(returnString);)

And then combine them for your answer.

You can check the code here http://tpcg.io/qdubRQ

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
GamingFelix
  • 239
  • 2
  • 10
  • Right, updated. Haven't used equals in a while :) – GamingFelix Dec 20 '18 at 00:20
  • 1
    @GBlodgett you're right. I've gotten way too used to Scala it seems. Quite embarrassing. But thanks for the help! I thought my solution was neat but seems while I was replying others written way more replies. :) – GamingFelix Dec 20 '18 at 00:30
  • This is quite nice, but unfortunately if the input is startOz("oz") then the output will be "z" instead of "oz". Is there a way to salvage this attempt to? –  Dec 20 '18 at 00:35
  • 1
    You could just declare a string and instead of println, concat the letter onto that that string. Which you then will return. As long as you do if in the right order it should work. – GamingFelix Dec 20 '18 at 00:37
  • 1
    @Dahaka there, I updated it. Instead of printing it, you can just return it. :) – GamingFelix Dec 20 '18 at 00:55
  • 1
    Found another issue for inputing a blank space, but easily fixed: http://tpcg.io/ochjJc –  Dec 20 '18 at 01:03
  • 1
    yep, nice. Could always just do a isEmpty, isDefined or nullCheck too. But your solution works too, for the problem. – GamingFelix Dec 20 '18 at 01:17
2
public String startOz(String str) {
  int len = str.length(); // calculating length
  if(len < 1) return new String("");
  if(len > 1 && str.charAt(0) == 'o' && str.charAt(1) == 'z') return new String("oz");  // checking if the string length is more than 2 and it starts with oz
  if(str.charAt(0) == 'o') return new String("o"); // if the string starts with o
  if(str.charAt(1) == 'z') return new String("z"); // if the string has 2nd char as z
  return new String(""); // nothing matched
}

Edit : Just a slight improvement, although the above solution got accepted but there would be a problem if the input str = "z" then it would give "StringIndexOutOfBoundsException" which should be avoided. So please edit the 6th line as if(len >= 1 && str.charAt(1) == 'z')then it would be perfect.

Brij Raj Kishore
  • 1,595
  • 1
  • 11
  • 24
1

I would break the problem into the two boolean tests you are performing (first is there at least one character and is the first character o, second are there are least two characters and the second one is z). I would use String.toCharArray() to make getting those characters easier. Then you can test those boolean conditions. Like,

public String startOz(String str) {
    if (str != null) {
        char[] arr = str.toLowerCase().toCharArray();
        boolean oTest = arr.length >= 1 && arr[0] == 'o';
        boolean zTest = arr.length >= 2 && arr[1] == 'z';
        if (oTest && zTest) {
            return "oz";
        } else if (oTest) {
            return "o";
        } else if (zTest) {
            return "z";
        }
    }
    return "";
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

You could try this:

String result = "";
if(str != null && !str.isEmpty()){
    result = (str.indexOf("o") == 0 ? "o" : "").concat(str.indexOf("z") == 1 ? "z" : "");
}
return result;
AnxGotta
  • 1,006
  • 7
  • 28
  • This looks smooth. But I don't understand what is the difference between str != null and !str.empty() . Isn't one of them enough? –  Dec 20 '18 at 00:26
  • 2
    No problem. The `str` variable can be `null` if it wasn't initialized or assigned a value. The `str` variable could also be an empty string, or `""`. See how I initialized `result` with an empty string `""`. That is the difference. I checked them both there because they're conditions that would result in an empty string response to your problem; so we don't have to do any more checks. – AnxGotta Dec 20 '18 at 00:29
1

You can try this i made some few edits to your code but finally got it working

public static String startOz(String str) {
    if(str.length()>=2 && str.substring(0,2).equals("oz"))
    {
        return "oz";
    }
    else if(str.length()>=2 && str.substring(1,2).equals("z"))
    {
        return "z";
    }
    else if (str.length()>=2 && str.substring(0,1).equals("o"))
    {
        return "o";
    }
    return "";
}
preciousbetine
  • 2,959
  • 3
  • 13
  • 29
  • 1
    It would work perfectly if "else if (str.length()>=2 && str.substring(0,1).equals("o")) " would have ">=1" //Is there a way to write the comments in code mode? –  Dec 20 '18 at 01:09