Skip to content

Instantly share code, notes, and snippets.

@Maxdw
Created May 9, 2019 13:45
Show Gist options
  • Save Maxdw/d71afd11db2df4f1297ad3722d6392ec to your computer and use it in GitHub Desktop.
Save Maxdw/d71afd11db2df4f1297ad3722d6392ec to your computer and use it in GitHub Desktop.
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