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.





Following are the test cases

Test cases Result Status
nTwice(Hello,2) Helo OK
nTwice(Chocolate,3) Choate OK
nTwice(java,1) ja OK

Java solution


package test;

public class Program18 {
	public static void main(String[] args) {
		Program18.nTwice("Hello", 2);
		Program18.nTwice("Chocolate", 3);
		Program18.nTwice("java", 1);
	}
	public static String nTwice(String str, int n) {
		return str.substring(0, n) + str.substring(str.length() - n, str.length());
	}
}

Javascript solution


const nTwice = (str, n) => {
    return str.substr(0, n) + str.substr(str.length - n, str.length);
}

console.log(nTwice("Hello", 2)); //Helo
console.log(nTwice("Chocolate", 3)); //Choate
console.log(nTwice("java", 1)); //ja




About the author

Bushan Sirgur

Well, I am Bushan Sirgur from Banglore, India. Currently, I am working as a Software Developer in a Service Base Company. I am interested in JAVA/J2EE, Angular 2, JavaScript, jQuery, MongoDB.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *