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

0 min read 82 words

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);
    }
}

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"));
    }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags