Java > String-1 > atFirst (CodingBat Solution)

Problem:

Given a string, return a string length 2 made of its first 2 chars. If the string length is less than 2, use '@' for the missing chars.

atFirst("hello") → "he"
atFirst("hi") → "hi"
atFirst("h") → "h@"


Solution:

public String atFirst(String str) {
  if (str.length() >= 2)
    return str.substring(0,2);
  else if (str.length() == 1)
    return str + "@";
  else
    return "@@";
}


4 comments :

  1. public String atFirst(String str) {

    if(str.equals(""))
    return str + "@" +"@";

    if(str.length()<2)
    return str +"@";

    String s = str.substring(0,2);
    return s;
    }

    ReplyDelete
  2. public String atFirst(String str) {
    if(str.length()==0)
    {
    return "@@";
    }
    if(str.length()<2)
    {
    return str+"@";
    }
    return str.substring(0,2);

    }

    ReplyDelete
  3. public String atFirst(String str) {
    return str.length()>=2?str.substring(0,2):str.length()==1?str+"@":str+"@@";
    }

    ReplyDelete
  4. public String atFirst(String str) {
    if(str.isEmpty()){
    return "@@";
    }
    if(str.length() == 1){
    return str + '@';
    }
    return "" + str.charAt(0) + str.charAt(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