Saturday 11 April 2020

Extract digits from a string or text

Approach 1: Check each character whether it is a digit or not.
public static final String getDigits_Approach1(String str) {
         if (str == null || str.isEmpty()) {
                  return str;
         }

         StringBuilder stringBuilder = new StringBuilder();

         for (int i = 0; i < str.length(); i++) {
                  if (Character.isDigit(str.charAt(i))) {
                           stringBuilder.append(str.charAt(i));
                  }
         }

         return stringBuilder.toString();
}

Approach 2: Using Regular Expression.
public static final String getDigits_Approach2(String str) {
         if (str == null || str.isEmpty()) {
                  return str;
         }

         return str.replaceAll("\\D+", "");
}

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

public class StringUtil {

 public static String getDigits_Approach1(String str) {
  if (str == null || str.isEmpty()) {
   return str;
  }

  StringBuilder stringBuilder = new StringBuilder();

  for (int i = 0; i < str.length(); i++) {
   if (Character.isDigit(str.charAt(i))) {
    stringBuilder.append(str.charAt(i));
   }
  }

  return stringBuilder.toString();
 }

 public static String getDigits_Approach2(String str) {
  if (str == null || str.isEmpty()) {
   return str;
  }

  return str.replaceAll("\\D+", "");
 }
}


StringUtilTest.java

package com.sample.app.utils;

import static org.junit.Assert.*;

import org.junit.Test;

import static com.smaple.app.utils.StringUtil.getDigits_Approach1;
import static com.smaple.app.utils.StringUtil.getDigits_Approach2;

public class StringUtilTest {

 @Test
 public void inputIsNull() {
  String text = null;
  
  String result1 = getDigits_Approach1(text);
  String result2 = getDigits_Approach2(text);
  
  assertNull(result1);
  assertNull(result2);
 }
 
 @Test
 public void inputIsEmpty() {
  String text = "";
  
  String result1 = getDigits_Approach1(text);
  String result2 = getDigits_Approach2(text);
  
  assertEquals(text, result1);
  assertEquals(text, result2);
 }
 
 @Test
 public void inputIsNotEmpty() {
  String text = "a12B34)(*1";
  String expected = "12341";
  
  String result1 = getDigits_Approach1(text);
  String result2 = getDigits_Approach2(text);
  
  assertEquals(expected, result1);
  assertEquals(expected, result2);
 }
}


You may like

No comments:

Post a Comment