How to return a string made of the first 2 chars with given conditions [duplicate]

  • A+

This question already has an answer here:

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?


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


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: