Java > Warmup-2 > stringBits (CodingBat Solution)

Problem:

Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".

stringBits("Hello") → "Hlo"
stringBits("Hi") → "H"
stringBits("Heeololeo") → "Hello"


Solution:

public String stringBits(String str) {
  int len = str.length();
  String temp = "";
  
  for (int i = 0; i < len; i = i + 2) {
    temp += str.charAt(i);
  }
  return temp;
}

3 comments:

  1. String temp="";
    for(int i=0; i<str.length(); i+=2){
    temp+=str.substring(i,i+1);
    }
    return temp;

    ReplyDelete
  2. With Regex

    public String stringBits(String str) {
    return str.replaceAll("(.).", "$1");
    }

    ReplyDelete