Question

The int input represents a number k, and the method should replace the kth occurrence of the first char input with the second char input. If the first char does not occur at least k times, then nothing is replaced.

public class HW2{
    public static String replaceKth(char a, char b, int k, String c){
        StringBuilder builder = new StringBuilder();
        int occ = 0;
        for(int i = 0; i < c.length(); i = i + 1){
            if (c.charAt(i) == a){
                occ = occ + 1;
                if(occ == k){
                    builder.setCharAt(i, b);
                }
            }
        }
        return builder.toString();
    }
}

When I tried to test:

HW2.replaceKth(a, b, 3, "aabaa")
Static Error: Undefined name 'a'

yep I define a and another error appears

HW2.replaceKth('a', 'a', 3, "aabaa")
java.lang.StringIndexOutOfBoundsException: String index out of range: 3
    at java.lang.AbstractStringBuilder.setCharAt(AbstractStringBuilder.java:347)
    at java.lang.StringBuilder.setCharAt(StringBuilder.java:55)
    at HW2.replaceKth(HW2.java:15)
> 
Was it helpful?

Solution

You never set the builder instance equal to your String object that you wanted to modify.

public static String replaceKth(char a, char b, int k, String c){
    StringBuilder builder = new StringBuilder(c);
    int occ = 0;
    for(int i = 0; i < c.length(); i++){
        if (c.charAt(i) == a){
            occ = occ + 1;
            if(occ == k){
                builder.setCharAt(i, b);
            }
        }
    }
    return builder.toString();
}

OTHER TIPS

Without single-quotes, a is just a variable name, which appears not to be defined here.

When you call replaceKth, either define a and b to be a chars with specific values, or pass char literals, each enclosed in single-quotes.

char a = 'a';
char b = 'b';

OR

HW2.replaceKth('a', 'b', 3, "aabaa");

It looks like your error is because you are sending a variable a and not a letter a.

a is a variable you didn't declare. Either make one, or use quotes around the letters when calling the method.

You are not converting your String to StringBuilder

Change the code line as

 StringBuilder builder = new StringBuilder(c);

you can do like this to replace the character at an index

public class StringTest {
    public static void main(String[] args) {
        System.out.println(StringTest.replaceKth('a', 'b', 3, "aabaa"));
    }

    public static String replaceKth(char a, char b, int k, String c){
        StringBuilder builder = new StringBuilder(c);
        if(builder.charAt(k)==a){
            builder.setCharAt(k, b);
        }
        return builder.toString();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top