Saturday, May 3, 2014

Use of Substring

Ques:Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged. Note: use .equals() to compare 2 strings. 


notString("candy") → "not candy"
notString("x") → "not x"
notString("not bad") → "not bad"


Ans:

public String notString(String str) {
if (str.contains("not")){
       if(str.substring(0,3).equals("not")){return str;
           }else{return "not "+str;}
       }else{return "not "+str;}
}

No comments:

Post a Comment