Trim characters in Java
Solution 1
Apache Commons has a great StringUtils class (org.apache.commons.lang.StringUtils). In StringUtils
there is a strip(String, String)
method that will do what you want.
I highly recommend using Apache Commons anyway, especially the Collections and Lang libraries.
Solution 2
This does what you want:
public static void main (String[] args) {
String a = "\\joe\\jill\\";
String b = a.replaceAll("\\\\$", "").replaceAll("^\\\\", "");
System.out.println(b);
}
The $
is used to remove the sequence in the end of string. The ^
is used to remove in the beggining.
As an alternative, you can use the syntax:
String b = a.replaceAll("\\\\$|^\\\\", "");
The |
means "or".
In case you want to trim other chars, just adapt the regex:
String b = a.replaceAll("y$|^x", ""); // will remove all the y from the end and x from the beggining
Solution 3
CharMatcher
– Google Guava
In the past, I'd second Colins’ Apache commons-lang answer. But now that Google’s guava-libraries is released, the CharMatcher class will do what you want quite nicely:
String j = CharMatcher.is('\\').trimFrom("\\joe\\jill\\");
// j is now joe\jill
CharMatcher has a very simple and powerful set of APIs as well as some predefined constants which make manipulation very easy. For example:
CharMatcher.is(':').countIn("a:b:c"); // returns 2
CharMatcher.isNot(':').countIn("a:b:c"); // returns 3
CharMatcher.inRange('a', 'b').countIn("a:b:c"); // returns 2
CharMatcher.DIGIT.retainFrom("a12b34"); // returns "1234"
CharMatcher.ASCII.negate().removeFrom("a®¶b"); // returns "ab";
Very nice stuff.
Solution 4
Here is another non-regexp, non-super-awesome, non-super-optimized, however very easy to understand non-external-lib solution:
public static String trimStringByString(String text, String trimBy) {
int beginIndex = 0;
int endIndex = text.length();
while (text.substring(beginIndex, endIndex).startsWith(trimBy)) {
beginIndex += trimBy.length();
}
while (text.substring(beginIndex, endIndex).endsWith(trimBy)) {
endIndex -= trimBy.length();
}
return text.substring(beginIndex, endIndex);
}
Usage:
String trimmedString = trimStringByString(stringToTrim, "/");
Solution 5
You could use removeStart
and removeEnd
from Apache Commons Lang StringUtils
Related videos on Youtube
Comments
-
Oleksandr almost 2 years
How can I trim characters in Java?
e.g.String j = “\joe\jill\”.Trim(new char[] {“\”});
j should be
"joe\jill"
String j = “jack\joe\jill\”.Trim("jack");
j should be
"\joe\jill\"
etc
-
OscarRyz over 14 yearsWhat should
\\\\joe\\jill\\\\` should return?
joe\\jill` ?? -
Oleksandr over 14 years@Oscar yes. Like the trim in .net
-
Esko over 14 yearsI don't think this operation is called trimming...
-
aristotll over 6 yearsBut I just search trim char to find this question, hooray.
-
-
Brett Widmeier over 14 years"answer.length - trimChar.length - 1" actually
-
Pindatjuh over 14 yearsNot really optimized. I wouldn't use this.
-
Alex B over 14 years@BrettWidmeier I think I've got this write.
trim( "smiles", "les" )
yieldssmi
andtrim( "smiles", "s" )
yieldsmile
. -
rantingmong over 14 yearssure it is :D i meant a trim function that takes string as the question says
-
Lawrence Dol over 14 yearsI can't imagine a more inefficient way to solve this problem.
-
Alex B over 14 years@SoftwareMonkey I agree that it is not the most efficient solution, but context is helpful. On my machine, 10 million runs of
trim( "smiles", "s" );
take 547ms and 10 million runs of" mile ".trim()
take 248 ms. My solution is 1/2 as fast asString.trim()
and still 10 Million runs complete in about half a second. -
Alex B over 14 years@SoftwareMonkey The regex numbers are that
"smiles".replaceAll("s$|^s","")
run 10 million times takes 12,306 ms (~48 times slower thanString.trim()
and ~24 times slower than my implementation) -
Lawrence Dol over 14 years@Alex: I will take back my down-vote if you add a note that it should be optimized for the common-case of trimming a single character; I will up-vote it if you amend the code to so optimize (given that what is being asked for a is a re-usable library method).
-
Lawrence Dol over 14 years(and by "a single character" I mean any number of a single character from either end... IOW, when trimChar is length 1). Also trimChar is a bad name for that param... should likely be trimString or trimValue.
-
Alex B over 14 years@SoftwareMonkey: I appreciate the feedback. I'll add a comment about optimizing for the problem domain, but I didn't see any context for how this would be used in the original question or how many characters would be stripped (one example had a single character, and one example had a string). Good call on the name of trimChar.
-
Lawrence Dol over 14 yearsYour comparison to regex is not really fair or realistic; since the form used will compile the regex every time. If one were doing this frequently, one would create the regex and reuse the matcher, as the JavaDoc suggests:
An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression Pattern.compile(regex).matcher(str).replaceAll(repl)
. -
Alex B over 14 years@SoftwareMonkey: Great point! I took the regex example from @PauloGuedes code. I added numbers for the compiled regex version to my timing section.
-
Basil Bourque over 9 years👍 Do check out the CharMatcher in Google Guava. Slick stuff. Clever use of Predicate syntax. Makes it easy to specify which of the various definitions of whitespace, invisible, and control characters you have in mind. The doc links to an interesting spreadsheet listing some various definitions of whitespace.
-
Eric over 8 yearsReally nice solution.
-
EricG about 7 yearsI think you need to add the
\\
, i.e."\\y$|^\\x"
-
Bipul Roy almost 6 yearsBoss, in your last line it would be return inString.substring( from , to + 1 );
-
SparK almost 5 yearsdon't you mean
"\\\\+$"
?