如何在一段文字中重复每个字母?在Java中[英] How to repeat each of the individual letters in a piece of text? in Java

问题描述

如果文本为"dean"且乘数为 3,则在口吃中由提供的乘数指定的次数,结果将是"dddeeeaaannn".

public static void repeatLetters()
{
   String text = "dean";
   int n = 3;
   StringBuilder repeat = new StringBuilder(text);

   for (int i = 0; i < n; i++)
   {
      repeat.append("dean");
   }

   System.out.println(text);
}

没有得到所需的结果.我做错了什么?

推荐答案

您只是为其中的每个字符附加字符串本身 n 次.您需要遍历字符串并将每个字符附加 n 次.

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);
}

另外,另一种解决方案是使用正则表达式.

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));
}

本文地址:https://www.itbaoku.cn/post/978530.html