E
E
Erik Mironov2020-07-31 05:44:36
Java
Erik Mironov, 2020-07-31 05:44:36

How to output a string in the required format?

Task: Implement a method that takes a string as a parameter and increases the number of each character in the string by N times, where N is the position of the character in the string, and output in the format: string("abcde") -> A-Bb-Ccc-Dddd- Eeeee. I implemented the algorithm for increasing the number of characters in a string by N, but I don’t understand how I can output a string in this format. Point in the right direction, please.

public static void main(String[] args) {
        repeatChar("abcde");
    }


    public static String repeatChar (String s) {
        StringBuilder repeat = new StringBuilder();
        for(int i = 0; i < s.length(); i++){
            for(int j = -1; j < s.indexOf(s.charAt(i)); j++){
                repeat.append(s.charAt(i));               
            }
        }
           String str = repeat.toString();
        return s;
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Orkhan, 2020-07-31
@Erik_Mironov

You have a problem in the repeatChar() method.
If the algorithm itself is implemented correctly, then you just need to return a string

public static String repeatChar (String s) {
    StringBuilder repeat = new StringBuilder();
    for(int i = 0; i < s.length(); i++){
        for(int j = -1; j < s.indexOf(s.charAt(i)); j++){
            repeat.append(s.charAt(i));
        }
    }
    return repeat.toString();
}

And then it turns out. that you are taking an argument s and returning the same argument, instead of StringBuilder repeat

I
Ivan Solomennikov, 2020-07-31
@ivsol

You need to return str, or as already mentioned above in repeat.toString();order not to create a new line in the method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question