Java > Warmup-2 > altPairs (CodingBat Solution)

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;
}


5 comments :

  1. public String altPairs(String str) {

    String ans="";

    for (int i =0; i<str.length();i++){
    ans += str.charAt(i);
    if(i%2!=0) i+=2;
    }

    return ans;
    }

    ReplyDelete
  2. public String altPairs(String str) {
    String 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;
    }

    ReplyDelete
  3. public String altPairs(String str) {
    String 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;
    }

    ReplyDelete
  4. public String altPairs(String str) {
    String word = "";

    for(int i = 0; i < str.length(); i++){
    if(i % 4 == 0 || i % 4 == 1) word+= str.charAt(i);
    }
    return word;
    }

    ReplyDelete
  5. public String altPairs(String str) {
    int 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;
    }

    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