简体   繁体   English

如何重复每个字符重复次数递减的字符串?

[英]How do I repeat a string where each character is repeated a decreasing number of times?

Ah yes, I am back with another Java question.是的,我又回到了另一个 Java 问题。 So here I am supposed to repeat a string where its characters repeat a decreasing number of times.所以在这里我应该重复一个字符串,它的字符重复次数减少。 The first character should be repeated the string's length number of times.第一个字符应该重复字符串的长度次数。

Here is an example of what the output should look like:这是输出应该是什么样子的示例:

HHHHH
oooo
www
dd
y

What should I do next based on the code I have written below?根据我下面写的代码,我接下来应该做什么?

String go( String a) 
{
  String y = "";
  for (int i = 0; i < a.length(); i++)
  {
    for (int j = 0; j < a.length(); j++)
    {
      y = y + a.charAt(i);
    }
    if (i == a.length() - 1)
    {
      y = y + "";
    }
    else
    {
      y = y + "\n";
    }
  }
  return y;
}

Feel free to point out any obvious mistakes I have made.随意指出我犯过的任何明显错误。 I am new to Java and just learned that Java and Javascript are not the same thing!我是 Java 新手,刚刚了解到 Java 和 Javascript 不是一回事!

We can maintain two counters - 1 for extracting the character from string (characterLoc) and the other for specifying the number of times a character is to be repeated (repCount).我们可以维护两个计数器 - 一个用于从字符串中提取字符 (characterLoc),另一个用于指定字符重复的次数 (repCount)。

The outer while loop is used for extracting the character and inner loop is used for repeating the extracted character a specified number of times.外循环用于提取字符,内循环用于将提取的字符重复指定次数。

public static void main(String[] args) {
    String str = "Howdy";
    int characterLoc = 0;
    int repCount = str.length();

    while (characterLoc < str.length()) {
        for (int x = repCount; x > 0; x--) {
            System.out.print(str.charAt(characterLoc));
        }
        characterLoc++;
        repCount--;
        System.out.println();
    }
}

When I ran the code you posted in your question, I got this result:当我运行你在你的问题中发布的代码时,我得到了这个结果:

HHHHH
ooooo
wwwww
ddddd
yyyyy

which is not what you want.这不是你想要的。
In order to get what you want, you simply need to make one change in your code.为了得到你想要的东西,你只需要在你的代码中做一个改变。 You need to change the inner for loop.您需要更改内部for循环。 Here is your code with the required addition.这是带有所需添加的代码。

private static String go(String a) {
    String y = "";
    for (int i = 0; i < a.length(); i++) {
        for (int j = 0; j < a.length() - i; j++) { // change here
            y = y + a.charAt(i);
        }
        if (i == a.length() - 1) {
            y = y + "";
        }
        else {
            y = y + "\n";
        }
    }
    return y;        
}

When you run that code, it produces the following output.当您运行该代码时,它会产生以下输出。

HHHHH
oooo
www
dd
y

which is what you want, isn't it?你想要的,不是吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM