In Java, I want to trim multiple specified characters from only the beginning and end.

I want to trim multiple specified characters from only the beginning and end.


Unless you can't use apache.commons.lang The code below does not come into play.

Use the strip method. It's fast.

From this point onward, it is recommended only for those who like things.

For example. I want to get elements other than full-width spaces, half-width spaces, and tab characters.

I think it's common. ReplaceAll? "I don't want to replace half-width spaces in the elements I want to retrieve." So I can't use it.

At that time, I wrote the following code. I hope it helps the copy programmer.

	private String trim(String target) {
		if (target == null || target.isEmpty() || TRIM_CHARS.isEmpty()) {
			return target;
		final char[] chars = target.toCharArray();
		int trimHeadIndex = 0;
		int trimTailIndex = 0;
		for (int i = 0; i < chars.length; i++) {
			if (!TRIM_CHARS.contains(chars[i])) {
				trimHeadIndex = i;
		for (int t = chars.length; t > 0; t--) {
			if (!TRIM_CHARS.contains(chars[t - 1])) {
				trimTailIndex = t;
		return target.substring(trimHeadIndex, trimTailIndex);

Although TRIM_CHARS is an array For ease of addition, first with List, After finishing the operation, set it to Collections # unmodifiableList and set it to` It may be better to have it as a constant. (Not just the final modifier)

I thought again, "I think I can do it with regular expressions." Is it okay because it has been realized?

By the way, even if I experimented with surrogate pair characters, it worked as expected. (Unexpected)

Recommended Posts

In Java, I want to trim multiple specified characters from only the beginning and end.
[Ruby] I want to output only the odd-numbered characters in the character string
[Java] I want to calculate the difference from the date
[Java] Delete the specified number of characters from the end of StringBuilder
I want to simplify the conditional if-else statement in Java
I want to give edit and delete permissions only to the poster
I want to return to the previous screen with kotlin and java!
[Java] I want to perform distinct with the key in the object
[Android] I want to get the listener from the button in ListView
[Ruby] I want to extract only the value of the hash and only the key
I want to get the IP address when connecting to Wi-Fi in Java
I translated the grammar of R and Java [Updated from time to time]
Run R from Java I want to run rJava
I want to send an email in Java.
rsync4j --I want to touch rsync in Java.
I want to write quickly from java to sqlite
I want to get the value in Ruby
Development memo ~ I want to display only the first image posted multiple times ~
I want to get only the time from Time type data ...! [Strftime] * Additional notes
I want to do something like "cls" in Java
I want to embed any TraceId in the log
Tokoro I rewrote in the migration from Wicket 7 to 8
I want to use ES2015 in Java too! → (´ ・ ω ・ `)
Java classes and instances to understand in the figure
I want to transition screens with kotlin and java!
I tried to implement the Euclidean algorithm in Java
I want to change the path after new registration after logging in with multiple devises.
I want to morphologically analyze the log in the DB and put it in the DB to classify messages 1
[Android Studio] I want to set restrictions on the values registered in EditText [Java]
# 1_JAVA I want to get the index number by specifying one character in the character string.
I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.
JSON in Java and Jackson Part 1 Return JSON from the server
I want to set the conditions to be displayed in collection_check_boxes
[JDBC] I tried to access the SQLite3 database from Java.
I tried to summarize the basics of kotlin and java
I want to convert characters ...
I want to bring Tomcat to the server and start the application
I want to make a list with kotlin and java!
I want to call a method and count the number
I want to make a function with kotlin and java!
I want to use the Java 8 DateTime API slowly (now)
What I did in the version upgrade from Ruby 2.5.2 to 2.7.1
Correct the character code in Java and read from the URL
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
I want to return a type different from the input element with Java8 StreamAPI reduce ()
I want to transition to the same screen in the saved state
I want to implement various functions with kotlin and java!
I want to recreate the contents of assets from scratch in the environment built with capistrano
I want to return multiple return values for the input argument
[Java] I want to check that the elements in the list are null or empty [Collection Utils]
[Wire Mock] I want to set up a stub / mock server in Java and perform E2E tests.
I implemented the code to learn multiple images at once in the Watson Visual Recognition Collection in Java.
If you want to change the Java development environment from Eclipse
What I did in the migration from Spring Boot 1.4 series to 2.0 series
I want to display the images under assets/images in the production environment
What I did in the migration from Spring Boot 1.5 series to 2.0 series
From fledgling Java (3 years) to Node.js (4 years). And the impression of returning to Java
I tried to summarize the methods of Java String and StringBuilder
I want to remove the top margin in Grouped UITableView (swift)
[Java] How to convert from String to Path type and get the path
I want to change the value of Attribute in Selenium of Ruby