Skip to content

Instantly share code, notes, and snippets.

@Maxdw
Created May 9, 2019
Embed
What would you like to do?
package com.github.gist.maxdw;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
class Trim {
/**
* All characters on both the left side and the right side
* of the string that appear in the provided characters string
* argument will be trimmed until a character in string does
* not appear in the characters string argument (individually
* for each side).
*
* @param string e.g. 'cbabc'
* @param characters 'cb'
* @return 'a'
*/
static String both(String string, String characters) {
string = Trim.left(string, characters);
string = Trim.right(string, characters);
return string;
}
/**
* All characters of the right side of the provided string
* that appear in the provided characters string argument
* will be trimmed until a character in string does not
* appear in the characters string argument.
*
* @param string e.g. 'abc'
* @param characters e.g. 'cb'
* @return 'a'
*/
static String right(String string, String characters) {
CharacterIterator it = new StringCharacterIterator(string);
int beginIndex = it.getBeginIndex();
int endIndex = it.getEndIndex();
it.last();
do {
char chr = it.current();
if (!characters.contains(String.valueOf(chr))) {
break;
}
endIndex--;
} while (it.previous() != CharacterIterator.DONE);
return string.substring(beginIndex, endIndex);
}
/**
* All characters of the left side of the provided string
* that appear in the provided characters string argument
* will be trimmed until a character in string does not
* appear in the characters string argument.
*
* @param string e.g. 'abc'
* @param characters 'ba'
* @return 'a'
*/
static String left(String string, String characters) {
CharacterIterator it = new StringCharacterIterator(string);
int beginIndex = it.getBeginIndex();
int endIndex = it.getEndIndex();
do {
char chr = it.current();
if (!characters.contains(String.valueOf(chr))) {
break;
}
beginIndex++;
} while(it.next() != CharacterIterator.DONE);
return string.substring(beginIndex, endIndex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment