Java > String-1 > nTwice (CodingBat Solution)

Problem:

Given a string and an int n, return a string made of the first and last n chars from the string. The string length will be at least n.

nTwice("Hello", 2) → "Helo"
nTwice("Chocolate", 3) → "Choate"
nTwice("Chocolate", 1) → "Ce"


Solution:

public String nTwice(String str, int n) {
  return str.substring(0,n) + str.substring(str.length()- n, str.length());
}


4 comments :

  1. public String nTwice(String str, int n) {
    return str.substring(0,n).concat(str.substring(str.length()-n));
    }

    ReplyDelete
  2. public String nTwice(String str, int n) {
    String a=str.substring(0,n);
    String b=str.substring(str.length()-n);
    return a+b;
    }

    ReplyDelete
  3. public String nTwice(String str, int n) {
    String res="";
    String fst=str.substring(0,n);
    String lst=str.substring(str.length()-n,str.length());
    return res=fst+lst;
    }

    ReplyDelete
  4. public String nTwice(String str, int n) {
    if(str=="")
    {
    return str;
    }
    else
    {
    int ub=str.length()-1;
    return str.substring(0,n) + str.substring(ub-n+1,str.length());
    }
    }

    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