How to Remove First and Last Character in a String in Java

The challenge

The goal is to create a function that removes the first and last characters of a string. You don’t have to worry with strings with less than two characters.

The solution in Java code

public class RemoveChars { public static String remove(String str) { return str.substring(1, str.length()-1); } }
Code language: Java (java)

Test cases to validate our Java solution

import org.junit.Test; import static org.junit.Assert.assertEquals; public class RemoveCharsTest { @Test public void testRemoval() { assertEquals("loquen", RemoveChars.remove("eloquent")); assertEquals("ountr", RemoveChars.remove("country")); assertEquals("erso", RemoveChars.remove("person")); assertEquals("lac", RemoveChars.remove("place")); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments