replace more than one char utitlizando . replace()

Asked

Viewed 91 times

3

I have the following function:

public String replaceCharToNull(int row, int colum)
{
    String result;
    
    result = (((String)jTableLoan.getModel().getValueAt(row, colum)).replace("x", ""));
    return result;
}

I need to remove two characters "x" and "%", it has a way of doing type one: .replace("x" || "%", ""));

Or

I need to create another function to replace the % instead of doing it in the same function?

2 answers

2


Depends on what you need.

I need to remove two "x" characters and "%"

That means you want to remove the x and the % regardless of where they are, or only if one is after the other (only if it is x%)?


Remove only x%

If to remove only x%, you can use your own replace:

System.out.println("abcx%123 blax%etc".replace("x%", "")); // abc123 blaetc

Of course use replaceAll, as suggested by another answer, also works. She cites that replaceAll accepts regex, which is true, but in this specific case it makes no difference, because using a fixed text like "x%", does not need a regular expression itself (ie, was mentioned an advantage that in the end was not used, because it is indifferent to use one or the other for this case - if you want to know more about regex, see here and here).

In fact replace for fixed texts is better because replaceAll treats any string as a regular expression, which means that an instance of Pattern, which is not one of the most "light" and "cheap" objects that exist. Roughly speaking, if you don’t need regex, don’t use it. If to replace a fixed string, prefer to use replace (of course for small programs the difference will be insignificant, but in larger applications, it may be worth taking into account).

And as already said, in this case will only be removed x%. If you have a x or a % separated, they will not be replaced:

System.out.println("abcx%123xbl%ax%etc".replace("x%", ""));    // abc123xbl%aetc
System.out.println("abcx%123xbl%ax%etc".replaceAll("x%", "")); // abc123xbl%aetc

Notice that he only removed the x%, but the x before the b and the % before the last a remained.


Remove x or %

If the idea is to remove the x or % whether they are together or not, then the approach is different.

One option is to use 2 calls from replace:

System.out.println("abcx%123xbl%ax%etc".replace("x", "").replace("%", "")); // abc123blaetc

The first removes all x and the second removes all %.

Another option is to use replaceAll, and in this case yes is "justified" the use of regex:

System.out.println("abcx%123xbl%ax%etc".replaceAll("[x%]", "")); // abc123blaetc

The expression [x%] is a character class, which means "the character x or the character %" (any of them). Therefore, any of them will be replaced by "" (which is the same as removing them). It is important to note that if I remove the brackets, the x% is treated as a fixed text and only removes the x%, but not the x and % separately.


One of the problems of calling replace several times each call creates a new String (in Java, strings are immutable and every method that "modifies" something actually returns another string).

Of course, for just two characters and a few small strings being executed a few times it won’t make much difference, but if the character list was longer, I would have to call replace several times, creating several intermediate strings. And use a regex (with replaceAll, even if it is only once) also has there your overhead.

Maybe it’s micro-optimization (or maybe it gets worse, or it doesn’t make a difference, just testing to find out), but a third alternative is to do the substitution manually, whether using a StringBuilder:

String original = "abcx%123xbl%ax%etc";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < original.length(); i++) {
    char c = original.charAt(i);
    if (c != 'x' && c != '%') {
        sb.append(c); // só adiciono na nova string se não for "x" nem "%"
    }
}
String nova = sb.toString();

Or building an array of char:

String original = "abcx%123xbl%ax%etc";
char[] chars = new char[original.length()];
int tamanhoNovo = 0;
for (int i = 0; i < original.length(); i++) {
    char c = original.charAt(i);
    if (c != 'x' && c != '%') {
        chars[tamanhoNovo] = c;
        tamanhoNovo++;
    }
}
String nova = new String(chars, 0, tamanhoNovo);
  • 1

    In my case, it was easier to solve using the System.out.println("abcx%123xbl%ax%etc".replace("x", "").replace("%", "")); , since my function can receive strings with the x or with %, You don’t get both at once, you get one or the other. Before continuing the code I will give a read on the links you left to understand more deeply how it works... As this code handles many conventions, I may have problems ahead of me. Thanks again, @hkotsubo

1

Use the replaceAll, it accepts regex. For example:

"abcx%123".replaceAll("x%", "")

The result will be "abc123".

  • Thank you very much ! But in that situation what would be regex ?

  • 1

    Regex (Regular Expression) is a mechanism for searching and replacing characters in a string. It is a very broad theme and can be used for more complex tests such as (for example) determining whether a string represents a valid email, or removing all non-numeric characters.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.