Saturday 11 April 2020

Java: Remove first character of a string

Using ‘subString’ method, you can extract the string except the first character.

Example
public static String removeFirstChar(String str) {
         if (str == null || str.isEmpty()) {
                  throw new IllegalArgumentException("Input must not be null or empty");
         }
        
         return str.substring(1);

}

StringUtil.java
package com.smaple.app.utils;

public class StringUtil {

 public static String removeFirstChar(String str) {
  if (str == null || str.isEmpty()) {
   throw new IllegalArgumentException("Input must not be null or empty");
  }

  return str.substring(1);

 }
}

StringUtilTest.java

package com.sample.app.utils;

import static com.smaple.app.utils.StringUtil.removeFirstChar;
import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class StringUtilTest {

 @Test(expected = IllegalArgumentException.class)
 public void inputIsNull() {
  String text = null;

  removeFirstChar(text);
 }

 @Test(expected = IllegalArgumentException.class)
 public void inputIsEmpty() {
  String text = "";

  removeFirstChar(text);
 }

 @Test
 public void inputLengthIs1() {
  String text = "a";
  String expected = "";
  
  String result = removeFirstChar(text);
  assertEquals(expected, result);
 }

 @Test
 public void inputLengthIsGreaterThan1() {
  String text = "hello";
  String expected = "ello";

  String result = removeFirstChar(text);

  assertEquals(expected, result);

 }
}


You may like

No comments:

Post a Comment