java(simple)warmup1

本文介绍了三种基本的字符串操作方法:在字符串前添加特定字符但保留原有条件不变、交换字符串首尾字符位置以及根据特定条件选择性地提取字符串开头的字符。通过具体示例展示了这些操作的实现过程。

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值