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

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact