Trim Characters in Java

Trim characters in Java

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.

Trim leading or trailing characters from a string?

You could use

Leading:

System.out.println("//test/me".replaceAll("^/+", ""));

Trailing:

System.out.println("//test/me//".replaceAll("/+$", ""));

Trim unwanted characters in a Java String

Here's a method that's more general purpose to remove a prefix and suffix from a string:

public static String trim (String str, String prefix, String suffix)
{
int indexOfLast = str.lastIndexOf(suffix);

// Note: you will want to do some error checking here
// in case the suffix does not occur in the passed in String

str = str.substring(0, indexOfLast);

return str.replaceFirst(prefix, "");
}

Usage:

String test = "ab-android-regression-4.4-git";
String trim = trim(test, "ab-", "-git"));

To remove the "-" and make uppercase, then just do:

trim = trim.replaceAll("-", " ").toUpperCase();

How to trim a string after a specific character in java

You can use:

result = result.split("\n")[0];

How to remove all characters before a specific character in Java?

You can use .substring():

String s = "the text=text";
String s1 = s.substring(s.indexOf("=") + 1);
s1.trim();

then s1 contains everything after = in the original string.

s1.trim()

.trim() removes spaces before the first character (which isn't a whitespace, such as letters, numbers etc.) of a string (leading spaces) and also removes spaces after the last character (trailing spaces).

How to trim Characters in Android?

Hy karan, you just have to do this for special characters:

String trim;
String trim = beforeTrim.replaceAll("[|?*<\">+\\[\\]/']", "");
System.out.println("After trimming"+" " +trim);

The result you will get is:

http://karan.development.com/Image_android/upload_image_14552.jpg

Hope this will help !

Java trim character and whitespaces

The simplest approach would be to just remove everything that is not a digit, using the regular expression non-digit character class (\D):

test_id = test_id.replaceAll("\\D", "");

Trimming multiple characters in a string

This will trim any number of quotes or spaces from the beginning or end of your string:

str = str.replaceAll("^[ \"]+|[ \"]+$", "");


Related Topics



Leave a reply



Submit