From 23980dd790e6de4fb59b60b370ac42a5a6dc065f Mon Sep 17 00:00:00 2001 From: Villu Ruusmann Date: Sat, 10 Mar 2018 13:09:17 +0200 Subject: [PATCH] Added StringUtil utility class See https://github.com/jpmml/jpmml-evaluator/issues/105 --- .../main/java/org/jpmml/model/StringUtil.java | 42 ++++++++++++++++++ .../java/org/jpmml/model/StringUtilTest.java | 43 +++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 pmml-model/src/main/java/org/jpmml/model/StringUtil.java create mode 100644 pmml-model/src/test/java/org/jpmml/model/StringUtilTest.java diff --git a/pmml-model/src/main/java/org/jpmml/model/StringUtil.java b/pmml-model/src/main/java/org/jpmml/model/StringUtil.java new file mode 100644 index 00000000..6e92e142 --- /dev/null +++ b/pmml-model/src/main/java/org/jpmml/model/StringUtil.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2018 Villu Ruusmann + */ +package org.jpmml.model; + +public class StringUtil { + + private StringUtil(){ + } + + /** + *

+ * Trims trailing whitespace from a string value. + * According to the PMML specification, + * the leading whitespace is significant, but the trailing whitespace isn't. + *

+ * + * @see Character#isWhitespace(char) + */ + static + public String trim(String string){ + int length = string.length(); + + int trimmedLength = length; + + while(trimmedLength > 0){ + char c = string.charAt(trimmedLength - 1); + + if(!Character.isWhitespace(c)){ + break; + } + + trimmedLength--; + } + + if(trimmedLength < length){ + string = string.substring(0, trimmedLength); + } + + return string; + } +} \ No newline at end of file diff --git a/pmml-model/src/test/java/org/jpmml/model/StringUtilTest.java b/pmml-model/src/test/java/org/jpmml/model/StringUtilTest.java new file mode 100644 index 00000000..fcb17ef2 --- /dev/null +++ b/pmml-model/src/test/java/org/jpmml/model/StringUtilTest.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2018 Villu Ruusmann + */ +package org.jpmml.model; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; + +public class StringUtilTest { + + @Test + public void trim(){ + String string = ""; + + assertSame(string, StringUtil.trim(string)); + + string = "token"; + + assertSame(string, StringUtil.trim(string)); + + string = "\ttoken"; + + assertSame(string, StringUtil.trim(string)); + + string = "token\n"; + + assertEquals("token", StringUtil.trim(string)); + + string = "token\r\n"; + + assertEquals("token", StringUtil.trim(string)); + + string = "\ttoken\n"; + + assertEquals("\ttoken", StringUtil.trim(string)); + + string = "\ttoken\r\n"; + + assertEquals("\ttoken", StringUtil.trim(string)); + } +} \ No newline at end of file