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”
.equals() use to compare the string ;
== don’t use to compare the string
public String notString(String str) {
if(str.length()<3) return "not "+str;
else if((str.substring(0,3)).equals("not")) return str;
else return "not " + str;
}
public String notString(String str) {
if (str.length() >= 3 && str.substring(0, 3).equals("not")) {
return str;
}
return "not " + str;
}
Given a string, return a new string where the first and last chars have been exchanged.
frontBack(“code”) → “eodc”
frontBack(“a”) → “a”
frontBack(“ab”) → “ba”
str.substring(k,k) for “”(null)
public String frontBack(String str) {
int n= str.length()-1;
if(n<=0) return str;
else if(n==1) return str.substring(1)+str.substring(0,1);
return str.substring(n)+str.substring(1,n)+str.substring(0,1);
}
public String frontBack(String str) {
if (str.length() <= 1) return str;
String mid = str.substring(1, str.length()-1);
// last + mid + first
return str.charAt(str.length()-1) + mid + str.charAt(0);
}
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”
use .charAt()==”k”(true)
don’t use .charAt().equals()(wrong)
public String startOz(String str) {
int n=str.length();
if(n>1 && str.substring(0,1).equals("o") && str.substring(1,2).equals("z")) return "oz";
else if(n>0 && str.substring(0,1).equals("o")) return "o";
else if(n>1 && str.substring(1,2).equals("z") ) return "z";
else return "";
Solution:
public String startOz(String str) {
String result = "";
if (str.length() >= 1 && str.charAt(0)=='o') {
result = result + str.charAt(0);
}
if (str.length() >= 2 && str.charAt(1)=='z') {
result = result + str.charAt(1);
}
return result;
}