Java > String-1 > twoChar (CodingBat Solution)

Problem:

Given a string and an index, return a string length 2 starting at the given index. If the index is too big or too small to define a string length 2, use the first 2 chars. The string length will be at least 2.

twoChar("java", 0) → "ja"
twoChar("java", 2) → "va"
twoChar("java", 3) → "ja"


Solution:

public String twoChar(String str, int index) {
  if (str.length() <= index + 1 || index < 0)
    return str.substring(0,2);
  else
    return str.substring(index, index + 2);
}


11 comments :

  1. This is v helpful thank uuuuuuu :-)

    ReplyDelete
  2. Mine included more of the unnecessary. Thank you for this one!

    public String twoChar(String str, int index) {
    if (index != str.length()) {
    return str.substring(0,2);
    }else{
    return str.substring(index, index+2);
    }
    }

    ReplyDelete
    Replies
    1. Please delete this one it is incorrect!

      Delete
    2. This one is ok.

      public String twoChar(String str, int index) {
      if (index == str.length()-1 ||
      index < 0 ||
      index >= str.length()) {
      return str.substring(0,2);
      }else{
      return str.substring(index, index+2);
      }
      }

      Delete
  3. public String twoChar(String str, int index) {
    return index+1=0?str.substring(index,index+2):str.substring(0,2);
    }
    // 😀

    ReplyDelete
    Replies
    1. public String twoChar(String str, int index) {
      return index+1=0?str.substring(index,index+2):str.substring(0,2);
      }
      // 😀

      Delete
    2. public String twoChar(String str, int index) {
      return index+1=0?str.substring(index,index+2):str.substring(0,2);
      }

      Delete
  4. public String twoChar(String str, int index) {
    if(index>=0 && index=2){
    return str.substring(index,index+2);
    }
    }
    return str.substring(0,2);

    }

    ReplyDelete
  5. public String twoChar(String str, int index) {
    if (str.length() >= index + 2&&index>=0) {
    return str.substring(index, index + 2);
    }
    return str.substring(0, 2);

    }

    ReplyDelete
  6. public String twoChar(String str, int index) {
    if(index<=0 || index>=str.length()-1) return str.substring(0,2);
    else return str.substring(index,index+2);
    }

    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