UMAR-MOBITSOLUTIONS
UMAR-MOBITSOLUTIONS

Reputation: 77984

android string Comparison problem?

friends,

i am facing an issue

when i display someone's post in android listview it shows me

someone\'s post

i want to remove \ from string and wrote following code which give me outofmemory error

if(val.contains("\\"))
        {
        val=val.replace("", "\\");
        }

any one guide me whats the soultion?

Upvotes: 1

Views: 588

Answers (2)

polygenelubricants
polygenelubricants

Reputation: 383696

Here's an excerpt from the documentation:

public String replace(CharSequence target, CharSequence replacement):
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".

So the error in this particular case is that you've swapped the arguments around.

System.out.println(  "a\\b"                    ); // "a\b"
System.out.println(  "a\\b".replace("", "\\")  ); // "\a\\\b\"
System.out.println(  "a\\b".replace("\\", "")  ); // "ab"

Note that you don't really need to do an if/contains check: if target is not found in your string, then no replacement will be made.

System.out.println("a+b".replace("\\", "")); // "a+b"

Upvotes: 1

slup
slup

Reputation: 5534

Doesn't replace work the other way round?

val = val.replace("\\", "");

Upvotes: 2

Related Questions