Problem:
Given a string, return a string made of the chars at indexes 0,1, 4,5, 8,9 ... so "kittens" yields "kien".
altPairs("kitten") → "kien"
altPairs("Chocolate") → "Chole"
altPairs("CodingHorror") → "Congrr"
Solution:
public String altPairs(String str) { String result = ""; for (int i=0; i<str.length(); i += 4) { int end = i + 2; if (end > str.length()) { end = str.length(); } result = result + str.substring(i, end); } return result; }
public String altPairs(String str) {
ReplyDeleteString ans="";
for (int i =0; i<str.length();i++){
ans += str.charAt(i);
if(i%2!=0) i+=2;
}
return ans;
}
public String altPairs(String str) {
ReplyDeleteString s1="";
for(int i=0; i<str.length();i++){
if(i%2==0) s1=s1+str.charAt(i);
if(i%2!=0){
s1=s1+str.charAt(i);
i=i+2;
}
}
return s1;
}
public String altPairs(String str) {
ReplyDeleteString s="";
int i=0;
while(i<str.length())
{
s=s+str.charAt(i);
i++;
if(i<str.length())
{
s=s+str.charAt(i);
i=i+3;
}
}
return s;
}
public String altPairs(String str) {
ReplyDeleteString word = "";
for(int i = 0; i < str.length(); i++){
if(i % 4 == 0 || i % 4 == 1) word+= str.charAt(i);
}
return word;
}
public String altPairs(String str) {
ReplyDeleteint count=0;
String str1="";
for(int i=0; i<str.length(); i++){
count++;
if(count == 3){
continue;
}
else if(count == 4 ){
count = 0;
}
else{
str1+=str.charAt(i);
}
}
return str1;
}