Java String trim has no effect - java

Java String trim is not removing a whitespace character for me.
String rank = (some method);
System.out.println("(" + rank + ")");
The output is (1 ). Notice the space to the right of the 1.
I have to remove the trailing space from the string rank but neither rank.trim() nor rank.replace(" ","") removes it.
The string rank just remains the same either way.
Edit: Full Code::
Document doc = Jsoup.connect("http://www.4icu.org/ca/").timeout(1000000).get();
Element table = doc.select("table").get(7);
Elements rows = table.select("tr");
for (Element row: rows) {
String rank = row.select("span").first().text().trim();
System.out.println("("+rank+")");
}
Why can't I remove that space?

The source code of that website shows the special html character . Try searching or replacing the following in your java String: \u00A0.
That's a non-breakable space. See: I have a string with "\u00a0", and I need to replace it with "" str_replace fails
rank = rank.replaceAll("\u00A0", "");
should work. Maybe add a double \\ instead of the \.

You should assign the result of trim back to the String variable. Otherwise it is not going to work, because strings in Java are immutable.
String orig = " quick brown fox ";
String trimmed = original.trim();

The character is a non-breaking space, and is thus not removed by the trim() method. Iterate through the characters and print the int value of each one, to know which character you must replace by an empty string to get what you want.

Are you assigning the String?
String rank = " blabla ";
rank = rank.trim();
Don't forget the second assignment, or your trimmed string will go nowhere.
You can look this sort of stuff up in the API as well: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim()
As you can see this method returns a String, like most methods that operate on a String do. They return the modified String and leave the original String in tact.

I had same problem and did little manipulation on java's trim() method.
You can use this code to trim:
public static String trimAdvanced(String value) {
Objects.requireNonNull(value);
int strLength = value.length();
int len = value.length();
int st = 0;
char[] val = value.toCharArray();
if (strLength == 0) {
return "";
}
while ((st < len) && (val[st] <= ' ') || (val[st] == '\u00A0')) {
st++;
if (st == strLength) {
break;
}
}
while ((st < len) && (val[len - 1] <= ' ') || (val[len - 1] == '\u00A0')) {
len--;
if (len == 0) {
break;
}
}
return (st > len) ? "" : ((st > 0) || (len < strLength)) ? value.substring(st, len) : value;
}

Trim function returns a new copy of the string, with leading and trailing whitespace omitted.
rank = rank.trim();// This will remove and save rank without leading and trailing spaces
will give the result you want.
Replace method will not work if you pass empty string for replacement.

Since String in java are immutable ie they cannot be changed. You need to reassign it to some temporary string. And then using that string you can convert it into int.
String temp=rank.trim()
int te= Integer.parseInt(temp)

Related

Why does this code execute?

Suppose I have a method called withoutX that, when given a string, removes first and last letters of the string if they are x.
My code is:
public String withoutX(String str) {
if(str.length()>0 && str.substring(0,1).equals("x")) {
str = str.substring(1);
}
if(str.length()>0 && str.substring(str.length()-1).equals("x")) {
str = str.substring(0,str.length()-1);
}
return str;
}
Why does this return the empty string ("") when str = "x"? Wouldn't the case when str = "x" fail after the first if statement because str = str.substring(1) references an index that is out of bounds (the max. index of str = "x" is 0)?
Wouldn't the case when str = "x" fail after the first if statement because str = str.substring(1) references an index that is out of bounds (the max. index of str = "x" is 0)?
No, because it's not out of bounds: the first (and second) parameters of substring can be anything up to the length() of the string, not just length() - 1. From the Javadoc:
[Throws] IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
That's larger than, not larger than or equal to.
It would be easier (and more efficient) to write this as:
int start = str.startsWith("x") ? 1 : 0;
int end = str.length() - (str.endsWith("x") && start < str.length() ? 1 : 0);
return str.substring(start, end);
The reason it's easier is that you're simply checking whether the string starts/ends with x; String provides methods to do that without constructing a substring first.
The reason it's more efficient is that it doesn't create intermediate substrings.
Let's go thorough the code step by step:
//str = "x"
if(str.length()>0 && str.substring(0,1).equals("x")) { // both true
str = str.substring(1);
//now: str = ""
}
if(str.length()>0 && str.substring(str.length()-1).equals("x")) { // str.length == 0.
//Since && does not evaluate the second parameter, everything is fine and if doesn't get called
}
return ""; //as str = ""

How to remove only trailing spaces of a string in Java and keep leading spaces?

The trim() function removes both the trailing and leading space, however, if I only want to remove the trailing space of a string, how can I do it?
Since JDK 11
If you are on JDK 11 or higher you should probably be using stripTrailing().
Earlier JDK versions
Using the regular expression \s++$, you can replace all trailing space characters (includes space and tab characters) with the empty string ("").
final String text = " foo ";
System.out.println(text.replaceFirst("\\s++$", ""));
Output
foo
Online demo.
Here's a breakdown of the regex:
\s – any whitespace character,
++ – match one or more of the previous token (possessively); i.e., match one or more whitespace character. The + pattern is used in its possessive form ++, which takes less time to detect the case when the pattern does not match.
$ – the end of the string.
Thus, the regular expression will match as much whitespace as it can that is followed directly by the end of the string: in other words, the trailing whitespace.
The investment into learning regular expressions will become more valuable, if you need to extend your requirements later on.
References
Java regular expression syntax
Another option is to use Apache Commons StringUtils, specifically StringUtils.stripEnd
String stripped = StringUtils.stripEnd(" my lousy string "," ");
I modified the original java.lang.String.trim() method a bit and it should work:
public String trim(String str) {
int len = str.length();
int st = 0;
char[] val = str.toCharArray();
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
return str.substring(st, len);
}
Test:
Test test = new Test();
String sample = " Hello World "; // A String with trailing and leading spaces
System.out.println(test.trim(sample) + " // No trailing spaces left");
Output:
Hello World // No trailing spaces left
As of JDK11 you can use stripTrailing:
String result = str.stripTrailing();
The most practical answer is #Micha's, Ahmad's is reverse of what you wanted so but here's what I came up with in case you'd prefer not to use unfamiliar tools or to see a concrete approach.
public String trimEnd( String myString ) {
for ( int i = myString.length() - 1; i >= 0; --i ) {
if ( myString.charAt(i) == ' ' ) {
continue;
} else {
myString = myString.substring( 0, ( i + 1 ) );
break;
}
}
return myString;
}
Used like:
public static void main( String[] args ) {
String s = " Some text here ";
System.out.println( s + "|" );
s = trimEnd( s );
System.out.println( s + "|" );
}
Output:
Some text here |
Some text here|
The best way in my opinion:
public static String trimEnd(String source) {
int pos = source.length() - 1;
while ((pos >= 0) && Character.isWhitespace(source.charAt(pos))) {
pos--;
}
pos++;
return (pos < source.length()) ? source.substring(0, pos) : source;
}
This does not allocate any temporary object to do the job and is faster than using a regular expression. Also it removes all whitespaces, not just ' '.
Here's a very short, efficient and easy-to-read version:
public static String trimTrailing(String str) {
if (str != null) {
for (int i = str.length() - 1; i >= 0; --i) {
if (str.charAt(i) != ' ') {
return str.substring(0, i + 1);
}
}
}
return str;
}
As an alternative to str.charAt(i) != ' ' you can also use !Character.isWhitespace(str.charAt(i) if you want to use a broader definition of whitespace.
Spring framework gives a useful org.springframework.util.StringUtils.
trimTrailingWhitespace
This code is intended to be read a easily as possible by using descriptive names (and avoiding regular expressions).
It does use Java 8's Optional so is not appropriate for everyone.
public static String removeTrailingWhitspace(String string) {
while (hasWhitespaceLastCharacter(string)) {
string = removeLastCharacter(string);
}
return string;
}
private static boolean hasWhitespaceLastCharacter(String string) {
return getLastCharacter(string)
.map(Character::isWhitespace)
.orElse(false);
}
private static Optional<Character> getLastCharacter(String string) {
if (string.isEmpty()) {
return Optional.empty();
}
return Optional.of(string.charAt(string.length() - 1));
}
private static String removeLastCharacter(String string) {
if (string.isEmpty()) {
throw new IllegalArgumentException("String must not be empty");
}
return string.substring(0, string.length() - 1);
}
String value= "Welcome to java ";
So we can use
value = value.trim();

Get the last three chars from any string - Java

I'm trying to take the last three chracters of any string and save it as another String variable. I'm having some tough time with my thought process.
String word = "onetwotwoone"
int length = word.length();
String new_word = id.getChars(length-3, length, buffer, index);
I don't know how to use the getChars method when it comes to buffer or index. Eclipse is making me have those in there. Any suggestions?
Why not just String substr = word.substring(word.length() - 3)?
Update
Please make sure you check that the String is at least 3 characters long before calling substring():
if (word.length() == 3) {
return word;
} else if (word.length() > 3) {
return word.substring(word.length() - 3);
} else {
// whatever is appropriate in this case
throw new IllegalArgumentException("word has fewer than 3 characters!");
}
I would consider right method from StringUtils class from Apache Commons Lang:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#right(java.lang.String,%20int)
It is safe. You will not get NullPointerException or StringIndexOutOfBoundsException.
Example usage:
StringUtils.right("abcdef", 3)
You can find more examples under the above link.
Here's some terse code that does the job using regex:
String last3 = str.replaceAll(".*?(.?.?.?)?$", "$1");
This code returns up to 3; if there are less than 3 it just returns the string.
This is how to do it safely without regex in one line:
String last3 = str == null || str.length() < 3 ?
str : str.substring(str.length() - 3);
By "safely", I mean without throwing an exception if the string is nulls or shorter than 3 characters (all the other answers are not "safe").
The above code is identical in effect to this code, if you prefer a more verbose, but potentially easier-to-read form:
String last3;
if (str == null || str.length() < 3) {
last3 = str;
} else {
last3 = str.substring(str.length() - 3);
}
String newString = originalString.substring(originalString.length()-3);
public String getLastThree(String myString) {
if(myString.length() > 3)
return myString.substring(myString.length()-3);
else
return myString;
}
If you want the String composed of the last three characters, you can use substring(int):
String new_word = word.substring(word.length() - 3);
If you actually want them as a character array, you should write
char[] buffer = new char[3];
int length = word.length();
word.getChars(length - 3, length, buffer, 0);
The first two arguments to getChars denote the portion of the string you want to extract. The third argument is the array into which that portion will be put. And the last argument gives the position in the buffer where the operation starts.
If the string has less than three characters, you'll get an exception in either of the above cases, so you might want to check for that.
Here is a method I use to get the last xx of a string:
public static String takeLast(String value, int count) {
if (value == null || value.trim().length() == 0 || count < 1) {
return "";
}
if (value.length() > count) {
return value.substring(value.length() - count);
} else {
return value;
}
}
Then use it like so:
String testStr = "this is a test string";
String last1 = takeLast(testStr, 1); //Output: g
String last4 = takeLast(testStr, 4); //Output: ring
This method would be helpful :
String rightPart(String text,int length)
{
if (text.length()<length) return text;
String raw = "";
for (int i = 1; i <= length; i++) {
raw += text.toCharArray()[text.length()-i];
}
return new StringBuilder(raw).reverse().toString();
}
The getChars string method does not return a value, instead it dumps its result into your buffer (or destination) array. The index parameter describes the start offset in your destination array.
Try this link for a more verbose description of the getChars method.
I agree with the others on this, I think substring would be a better way to handle what you're trying to accomplish.
You can use a substring
String word = "onetwotwoone"
int lenght = word.length(); //Note this should be function.
String numbers = word.substring(word.length() - 3);
Alternative way for "insufficient string length or null" save:
String numbers = defaultValue();
try{
numbers = word.substring(word.length() - 3);
} catch(Exception e) {
System.out.println("Insufficient String length");
}
This method will return the x amount of characters from the end.
public static String lastXChars(String v, int x) {
return v.length() <= x ? v : v.substring(v.length() - x);
}
//usage
System.out.println(lastXChars("stackoverflow", 4)); // flow

Remove trailing slash from String in Java

I am trying to remove the last character from a string, if it is a /. I am using a string array, temp[], to store the strings.
Here's my code:
char ch = ' ';
for (int st = 0; st < temp.length; st++)
{
ch = temp[st].charAt(temp[st].length()-1);
if (ch == '/')
temp[st] = temp[st].substring(0, temp[st].length()-1);
result2.append(temp[st]);
}
but i am getting
StringIndexOutOfBoundsException -1
What am I doing wrong?
Remove Last Character if it is / java
str = str.replaceAll("/$", "");
If you only want to remove a trailing '/', this should do it:
if (str.endsWith("/"))
return str.substring(0,str.length()-1);
else
return str;
You could do it with a regex using the replaceFirst(regex, string) method:
String newString = tmp.replaceFirst("/$", "");
The StringUtils have this subtle little method called: removeEnd(String str, String remove)
String result = StringUtils.removeEnd(string, "/")
It will remove the end of the string only if it is this searched snippet. Otherwise this method returns the same, unchanged string.
If you have empty String "" then temp[st].length()-1 == -1

How can I exchange the first and last characters of a string in Java?

I am practicing over the summer to try and get better and I am a little stuck on the following:
http://www.javabat.com/prob/p123384
Given a string, return a new string where the first and last chars have been exchanged.
Examples:
frontBack("code") → "eodc"
frontBack("a") → "a"
frontBack("ab") → "ba"
Code:
public String frontBack(String str)
{
String aString = "";
if (str.length() == 0){
return "";
}
char beginning = str.charAt(0);
char end = str.charAt(str.length() - 1);
str.replace(beginning, end);
str.replace(end, beginning);
return str;
}
Strings can be split into an array of chars and can be made with an array of chars. For more details on String objects, go to the Java API and click on String in the lower left pane. That pane is sorted alphabetically.
Edit: Since some people are being more thorough, I think I'll give additional details. Create a char array using String's .toCharArray() method. Take the first element and store it in a char, swap the first element with the last, and place the element you stored in a char into the last element into the array, then say:
String temp = new String(charArray);
and return that. This is assuming that charArray is your array of chars.
Rather than using the String.replace method, I'd suggest using the String.substring method to get the characters excluding the first and last letter, then concatenating the beginning and end characters.
Furthermore, the String.replace method will replace all occurrences of the specified character, and returns a new String with the said replacements. Since the return is not picked up in the code above, the String.replace calls really don't do much here.
This is because String in Java is immutable, therefore, the replace method cannot make any changes to the original String, which is the str variable in this case.
Also to add, this approach won't work well with Strings that have a length of 1. Using the approach above, a call to String.substring with the source String having a length of 1 will cause a StringIndexOutOfBoundsException, so that will also have to be taken care of as a special case, if the above approach is taken.
Frankly, the approach presented in indyK1ng's answer, where the char[] is obtained from the String and performing a simple swap of the beginning and end characters, then making a String from the modified char[] is starting to sound much more pleasant.
String instances in Java are immutable. This means that you cannot change the characters in a String; a different sequence of characters requires a new object. So, when you use the replace method, throw away the original string, and use the result of the method instead.
For this method, however, you probably want to convert the String instance to an array of characters (char[]), which are mutable. After swapping the desired characters, create a new String instance with that array.
A couple of hints:
Strings are immutable, meaning they cannot be changed. Hence, str.replace() does not change str, instead it returns a new string.
Maybe replace isn't the best... Consider frontBack("abcabc"): your function, if it were corrected, would replace 'a' with 'c' yielding "cbccbc", then 'c' with 'a' yielding "abaaba". That's not quite right!
The replace method in String actually returns a String, so if you were to insist on using replace, you'd do:
beginReplace = str.replace( beginning, end );
endReplace = beginReplace.replace( end, beginning );
return( str );
But this actually doesn't solve your specific problem, because replace replaces all occurences of a character in the string with its replacement.
For example, if my string was "apple" and I said "apple".replace( 'p', 'q' ), the resulting string would be "aqqle."
Yet another example without creating additional objects:
if (str.length() > 1) {
char[] chars = str.toCharArray();
// replace with swap()
char first = chars[0];
chars[0] = chars[chars.length - 1];
chars[chars.length - 1] = first;
str = new String(chars);
}
return str;
Edit: Performing the swap on length = 1 string is no-op.
Edit 2: dfa's change to copyValueOf did not make any sense as the Java source says in String.java: "// All public String constructors now copy the data." and the call is just delegated to a string constructor.
You could use a regex..
return str.replaceFirst("(.)(.*)(.)", "$3$2$1");
Just another, slightly different, approach, so you get a sense of the spectrum of possibilities. I commend your attention to the quick exit for short strings (instead of nesting the more-complicated processing in an if() clause), and to the use of String.format(), because it's a handy technique to have in your toolbox, not because it's notably better than regular "+" concatenation in this particular example.
public static String exchange(String s) {
int n = s.length();
if (n < 2)
return s;
return String.format("%s%s%s", s.charAt(n - 1), s.substring(1, n - 1), s.charAt(0));
}
Simple solution is:
public String frontBack(String str) {
if (str == null || str.length() == 0) {
return str;
}
char[] cs = str.toCharArray();
char first = cs[0];
cs[0] = cs[cs.length -1];
cs[cs.length -1] = first;
return new String(cs);
}
Using a character array (watch out for the nasty empty String or null String argument!)
Another solution uses StringBuilder (which is usually used to do String manupilation since String itself is immutable.
public String frontBack(String str) {
if (str == null || str.length() == 0) {
return str;
}
StringBuilder sb = new StringBuilder(str);
char first = sb.charAt(0);
sb.setCharAt(0, sb.charAt(sb.length()-1));
sb.setCharAt(sb.length()-1, first);
return sb.toString();
}
Yet another approach (more for instruction than actual use) is this one:
public String frontBack(String str) {
if (str == null || str.length() < 2) {
return str;
}
StringBuilder sb = new StringBuilder(str);
String sub = sb.substring(1, sb.length() -1);
return sb.reverse().replace(1, sb.length() -1, sub).toString();
}
Here the complete string is reversed and then the part that should not be reversed is replaced with the substring. ;)
if (s.length < 2) {
return s;
}
return s.subString(s.length - 1) + s.subString(1, s.length - 2) + s.subString(0, 1);
(untested, indexes may be of by one...
public String frontBack(String input)
{
return
input.substring(input.length() - 1) + // The last character
input.substring(1, input.length() - 1) + // plus the middle part
input.substring(0, 1); // plus the first character.
}
You can use a StringBuilder that represents "a mutable sequence of characters".
It has all methods needed to solve the problem: charAt, setCharAt, length and toString.
public String lastChars(String a, String b) {
if(a.length()>=1&&b.length()>=1){
String str = a.substring(0,1);
String str1 =b.substring(b.length()-1);
return str+str1;
}
else if(a.length()==0&&b.length()==0){
String v ="#";
String z ="#";
return v+z;
}
else if(a.length()==0&&b.length()>=1){
String s ="#";
String s1 = b.substring(b.length()-1);
return s+s1;
}
else if(a.length()>=1&&b.length()==0){
String f= a.substring(0,1);
String h = "#";
return f+h;
}
return a;
}
You can use this code:
public String frontBack(String str) {
if (str.length() <= 1)
return str;
String mid = str.substring(1, str.length()-1);
// last + mid + first
return str.charAt(str.length()-1) + mid + str.charAt(0);
}
class swap
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("no of elements in array");
int n=s.nextInt();
int a[]=new int[n];
System.out.println("Elements");
for(int i=0;i<n;i++)
{
a[i]=s.nextInt();
}
int b[]=new int[n];
for(int i=0;i<n;i++)
{
b[i]=a[i];
}
int end=n-1;
b[0]=b[end];
b[end]=a[0];
for(int i=0;i<n;i++)
{
System.out.println(b[i]);
}
}
}
if (str.length() <= 1) {
return str;
}
String mid = str.substring(1, str.length()-1);
return str.charAt(str.length()-1) + mid + str.charAt(0);
function frontBack(str: string) {
return str.slice(str.length - 1) + str.slice(1, -1) + str.slice(0, 1)
}
Slice will "cut out" the last letter. Counting the length of the string which is str.length -1, (plus) the reminder sliced string which starts at index 1 and is the last character which expressed at index -1, (plus) sliced last letter which is at index 0 through index 1.

Categories

Resources