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

查看:108
本文介绍了如何重复一段文字中的每个字母?在Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

未获得所需结果。我做错了什么?

Not getting the required result. What am I doing wrong?

推荐答案

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

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

这篇关于如何重复一段文字中的每个字母?在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆