How to repeat each of the individual letters in a piece of text? in Java

后端 未结 4 1279
悲&欢浪女
悲&欢浪女 2021-01-17 00:47

As in a stutter the number of times specified by the provided multiplier if the text was \"dean\" and the multiplier 3, the result would be \"ffffdeeeaaannn\".



        
4条回答
  •  旧时难觅i
    2021-01-17 00:56

    You are just appending the string itself n times for each character in it. You need to iterate through the string and append each character n times.

    public static void repeatLetters()
    {
        String text = "dean";
        int n = 3;
        StringBuilder repeat = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            for (int j = 0; j < n; j++) {
                repeat.append(text.charAt(i));
            }
        }
        System.out.println(repeat);
    }
    

    Also, another solution would be to use regular expressions.

    public static void repeatLetters()
    {
        String text = "dean", replace = "";
        int n = 3;
        for (int i = 0; i < n; i++) replace += "$1";
        System.out.println(text.replaceAll("(.)", replace));
    }
    

提交回复
热议问题