Sunday, 16 April 2017

Replace first occurrence of a string in Java

By using ‘replaceFirst’ method of String class, we can replace first occurrence of a string.

Ex
String result = input.replaceFirst(Pattern.quote(stringToReplace), stringToReplaceWith);

Following program used to replace first occurrence of a string. I added test cases also for your reference.

StringUtil.java
import java.util.regex.Pattern;

public class StringUtil {

 /**
  * Replace first occurrence of 'stringToReplace' with 'stringToReplaceWith'
  * in the given input.
  * 
  * @param input
  * @param stringToReplace
  * @param stringToReplaceWith
  * 
  * @return empty if input is null (or) empty, input if either of
  *         stringToReplace, stringToReplaceWith is null or empty, else
  *         return the string by replacing first occurrence of
  *         stringToReplace with stringToReplaceWith.
  */
 public static String replaceFirstOccurrenceOfString(String input, String stringToReplace,
   String stringToReplaceWith) {
  if (input == null || input.isEmpty()) {
   return "";
  }

  if (stringToReplace == null || stringToReplace.isEmpty() || stringToReplaceWith == null
    || stringToReplaceWith.isEmpty()) {
   return input;
  }

  String result = input.replaceFirst(Pattern.quote(stringToReplace), stringToReplaceWith);
  return result;
 }
}

StringUtilTest.java
import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class StringUtilTest {

 @Test
 public void replaceFirstOccurrenceOfString_emptyInput_emptyString(){
  String result = StringUtil.replaceFirstOccurrenceOfString("", "br", "duplicate");
  assertEquals(result, "");
 }
 
 @Test
 public void replaceFirstOccurrenceOfString_nullInput_emptyString(){
  String result = StringUtil.replaceFirstOccurrenceOfString(null, "br", "duplicate");
  assertEquals(result, "");
 }
 
 @Test
 public void replaceFirstOccurrenceOfString_stringToReplaceNull_emptyString(){
  String result = StringUtil.replaceFirstOccurrenceOfString("Abrakadabra", null, "duplicate");
  assertEquals(result, "Abrakadabra");
 }
 
 @Test
 public void replaceFirstOccurrenceOfString_stringToReplaceEmpty_emptyString(){
  String result = StringUtil.replaceFirstOccurrenceOfString("Abrakadabra", "", "duplicate");
  assertEquals(result, "Abrakadabra");
 }
 
 @Test
 public void replaceFirstOccurrenceOfString_stringToReplaceWithEmpty_emptyString(){
  String result = StringUtil.replaceFirstOccurrenceOfString("Abrakadabra", "br", "");
  assertEquals(result, "Abrakadabra");
 }
 
 @Test
 public void replaceFirstOccurrenceOfString_stringToReplaceWithNull_emptyString(){
  String result = StringUtil.replaceFirstOccurrenceOfString("Abrakadabra", "br", null);
  assertEquals(result, "Abrakadabra");
 }
 
 @Test
 public void replaceFirstOccurrenceOfString_properInpput_expectedString(){
  String result = StringUtil.replaceFirstOccurrenceOfString("Abrakadabra", "br", "duplicate");
  assertEquals(result, "Aduplicateakadabra");
 }
}