Friday, 14 August 2015

Check for proper string

Input: String appended with a number. Find whether the length of string excluding that number is equal to that number.


For Example: ‘Hello5’ is a proper string. ‘Hello6’ is not a proper string.
import java.util.Objects;

public class StringLength {

 public static boolean isStringProper(String str) {
  Objects.nonNull(str);
  StringBuilder builder = new StringBuilder();
  int i;

  /* If string is not as per pattern return false */
  if (!Character.isDigit(str.charAt(str.length() - 1)))
   return false;

  for (i = str.length() - 1; i > 0; i--) {
   if (Character.isDigit(str.charAt(i))) {
    builder = builder.append(str.charAt(i));
    continue;
   }
   break;
  }

  int number = Integer.parseInt(builder.reverse().toString());

  return (number == (i + 1));
 }
}


Following is the junit test case.
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class StringLengthTest {

 @Test
 public void test1() {
  assertTrue(StringLength.isStringProper("HelloWorld10"));
  assertTrue(StringLength.isStringProper("He2"));

  assertFalse(StringLength.isStringProper("HelloWorl10"));
  assertFalse(StringLength.isStringProper("HelloWorld"));
 }
}



No comments:

Post a Comment