Remove characters that are before another

Asked

Viewed 286 times

1

My teacher asked to make a method that cancels a character in a sentence using the # cancels the previous character, example:

Entree: PUO#C MIP#NO#AS

Exit: PUC MINAS

However, my code gives error when using the method replace or replaceAll to remove and swap for an empty character. Follow my code below:

public void Elimina(String frase) {

        for (int j = 0; j<frase.length(); j++) {
            if (frase.charAt(j) == '#') {
                frase = frase.replace(frase.charAt(j), '');
                frase = frase.replace(frase.charAt(j-1), '-');
            }
        }

        System.out.println(frase);      
    }

OBS:

frase = frase.replace(frase.charAt(j), ''); -> The mistake is this line on ''.

frase = frase.replace(frase.charAt(j-1), '-'); -> Here is to show that replacing the method works.

  • 2

    Share the code as text (and formatted here in the OS) instead of in image. And also make it clear which error happens. This makes your question more useful to those who research in the future.

  • 2

    Not only so that other people can search in the future, but it’s because it’s easier for you to post your code as code so that whoever answers can copy and paste this code than to want whoever answers to have to rewrite it all again.

  • 1

    charAt returns a char but replaceAll must receive String's, then the code doesn’t even compile. That said, why the character in the position j - 1 is being replaced by -? It’s not to eliminate him either?

  • 2

    @hkotsubo https://docs.oracle.com/en/javase/14/docs/api/java.base/java/lang/String.html#replace(char,char) - What does not compile is the ''.

  • Ah, I mistook it for replaceAll... Our failure

  • A number of great reasons not to post photos of codes, errors and logs and instead use text: https://pt.meta.stackoverflow.com/a/7817/3635 -- respect the tips and rules is to respect the site and the community, accept the tips, they are for the good of all. Welcome.

  • @Rafaeltavares reissued code and the error happens in replace by empty, as shown in the remark.

  • @hkotsubo, when I put '-' is to show that it works, but when I put '' it doesn’t work, just to highlight the error.

  • That hadn’t been made clear. Anyway, it was much easier to put the error message that appeared there (whenever it gives error, even more compilation, some message appears somewhere) :-)

  • @hkotsubo .

  • 1

    This is a build error so the error does not occur before compiling, but during :-) And always an error message appears somewhere (in many editors or has a separate console/window that shows errors or vc puts the cursor/mouse over the point that gives error and the message appears)

Show 6 more comments

2 answers

4

How is an exercise, probably the teacher wants you to use a loop, and then you can use the code of another answer.

But only to record an alternative:

public String elimina(String frase) {
    return frase.replaceAll(".#", "");    
}

I used the regex .#. The point corresponds to any character (except line breaks), so she takes any character followed by # and replaces with the empty string (which in practice is the same as removing these characters).

I also changed the method to return the string instead of printing it. So whoever calls the method gets the result and can do whatever you want with it (including printing, of course, but this responsibility should not remain in the function).

And I put the name starting with lowercase letter to be adhered to the Java code conventions.

Example of use:

System.out.println(elimina("PUO#C MIP#NO#AS"));

The above code prints "PUC MINAS".


The regex also already handles a corner case, which is when the string starts with #. In that case, I understand that the # should not be removed, since there is no previous character (and the above regex already does, because the substitution only occurs if there is a character before the #).

But if you want to remove the character # also if it is at the beginning of the string, just change the regex to ".?#". The ? indicates that the character before the # is optional.

  • 1

    Great explanation and did not know this method, very good for knowledge. Thank you.

2


I suggest you use a StringBuilder. You copy in it the characters one by one, but when you find one #, you delete the last.

public class Main {
    public static void main(String[] args) {
        System.out.println(elimina("PUO#C MIP#NO#AS"));
    }

    public static String elimina(String frase) {
        StringBuilder sb = new StringBuilder(frase.length());
        for (int j = 0; j < frase.length(); j++) {
            if (frase.charAt(j) == '#') {
                sb.deleteCharAt(sb.length() - 1);
            } else {
                sb.append(frase.charAt(j));
            }
        }
        return sb.toString();
    }
}

See it working on Ideone.

  • Victor Stafusa Thanks a lot for the help, I didn’t know the features of Stringbuilder, it helped a lot. Valeu!!!

  • @Victorhenrique If this answer solved your problem and there is no doubt left, click the " " which is to the left of the answer to mark it as accepted/correct, which also marks your question as solved/answered. Otherwise, feel free to comment.

Browser other questions tagged

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