Skip to content

Commit

Permalink
Added StringUtil utility class
Browse files Browse the repository at this point in the history
  • Loading branch information
vruusmann committed Mar 10, 2018
1 parent 913be50 commit 23980dd
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
42 changes: 42 additions & 0 deletions pmml-model/src/main/java/org/jpmml/model/StringUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Copyright (c) 2018 Villu Ruusmann
*/
package org.jpmml.model;

public class StringUtil {

private StringUtil(){
}

/**
* <p>
* Trims trailing whitespace from a string value.
* According to the PMML specification,
* the leading whitespace is significant, but the trailing whitespace isn't.
* </p>
*
* @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;
}
}
43 changes: 43 additions & 0 deletions pmml-model/src/test/java/org/jpmml/model/StringUtilTest.java
Original file line number Diff line number Diff line change
@@ -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));
}
}

0 comments on commit 23980dd

Please sign in to comment.