1

Im a beginner java programmer and I am stuck on a little problem with my university coursework.

Basically I have a string that I want to iterate through and replace all instances of the letter 'a' or 'e' with the letter 'z'. For example, if the original string was "hello alan", the final string should be "hzllo zlzn".

We need to do this using a character array which holds the characters 'a' and 'e' to test against the string.

I've included my code below, we need to use the charAt() method also.

public static void main(String[] args) {
    String a = ("what's the craic?");
    char letters[] = new char[]{'a', 't'};

    System.out.println("Before:" + a);
    System.out.println("After: " + removeCharacters(a, letters));
}

public static String removeCharacters(String sentence, char[] letters) {
    for (int i = 0; i < sentence.length(); i++) {
        for (int j = 0; j < letters.length; j++) {
            if (sentence.charAt(i) == letters[j]) {
                sentence = sentence.replace(sentence.charAt(i), 'z');
            } else {
                sentence = "No changes nessesary";
            }
        }
    }
    return sentence;
}

Please help me with this problem. Im not sure where I am going wrong! Thanks.

1
  • 1
    Couldn't you just use String#replaceAll for every character in the letters array? Commented Apr 23, 2020 at 18:41

4 Answers 4

2

Since you're forced to use charAt(...), one way would be like this:

public static String removeCharacters(String sentence, char[] letters) {
    String output = "";
    boolean wasChanged = false;

    for (int i = 0; i < sentence.length(); i++) {
        char ch = sentence.charAt(i);

        for (int j = 0; j < letters.length; j++)
            if (ch == letters[j]) {
                ch = 'z';
                wasChanged = true;
                break;
            }

        output += ch;
    }

    if (wasChanged)
        return output;
    else
        return "No changes necessary";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect solution, exactly what I was looking for as we are forced to use the charAt() method. Thanks for your help!
2

if You are allowed to use replaceAll as well

"hello alan".replaceAll( "[ae]", "z" );  // hzllo zlzn

In difference to replace uses replaceAll a Pattern internally, which is compiled from the first argument [ae] to find the part to substitute with the second argument z. This solution is elegantly short, but slow, because the Pattern has to be compiled each time replaceAll is called.


otherwise use a StringBuilder

char[] letters = new char[] { 'a', 'e' };
StringBuilder buf = new StringBuilder( "hello alan" );
IntStream.range( 0, buf.length() ).forEach( i -> {
  for( char c : letters )
    if( buf.charAt( i ) == c )
      buf.replace( i, i + 1, "z" );
} );
String s = buf.toString();  // hzllo zlzn

In difference to a String the contents of a StringBuilder is mutual (means you can change it). So it only has to be created once and all substitutions can be made in place.

1 Comment

Nice way of doing it, thanks for your help! Much appreciated.
2

Try this:

public static void main(String[] args) {
    String a = "hello alan";
    System.out.println("Before:" + a);
    System.out.println("After: " + removeCharacters(a));
}

public static String removeCharacters(String sentence) {
    if (!sentence.contains("a|e"))
        return "No changes necessary";
    return sentence.replaceAll("a|e", "z");
}

output 1:

Before:hello alan
After: hzllo zlzn

output 2:

Before:hi world
After: No changes necessary

1 Comment

Thanks for the help. Efficient solution and very clean code, much appreciated!
1

Since String::replace(char oldChar, char newChar) returns a new string resulting from replacing all occurrences of oldChar in this string with newChar, you do not need nested loops to do it. An efficient way of doing it can be as follows:

public static String removeCharacters(String sentence, char[] letters) {
    String copy = sentence;
    for (char letter : letters) {
        sentence = sentence.replace(letter, 'z');
    }
    if (sentence.equals(copy)) {
        sentence = "No changes nessesary";
    }
    return sentence;
}

Demo:

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(removeCharacters("hello stackoverflow", new char[] { 'a', 'e' }));
        System.out.println(removeCharacters("world", new char[] { 'a', 'e' }));
    }

    public static String removeCharacters(String sentence, char[] letters) {
        String copy = sentence;
        for (char letter : letters) {
            sentence = sentence.replace(letter, 'z');
        }
        if (sentence.equals(copy)) {
            sentence = "No changes nessesary";
        }
        return sentence;
    }
}

Output:

hzllo stzckovzrflow
No changes nessesary

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.