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; }
String temp="";
ReplyDeletefor(int i=0; i<str.length(); i+=2){
temp+=str.substring(i,i+1);
}
return temp;
With Regex
ReplyDeletepublic String stringBits(String str) {
return str.replaceAll("(.).", "$1");
}
Please explain
Delete