テキストの文字列を「n」回繰り返すことができるようにしたい:
このようなもの -
文字列「X」、 ユーザー入力 = n、 5 = n、 出力: XXXX
これが理にかなっているといいのですが...(できるだけ具体的にお願いします)
文字列を n 回繰り返すには、Apache commons のStringutilsクラスに repeat メソッドがあります。repeat メソッドでは、文字列と文字列を繰り返す回数、および繰り返される文字列を区切るセパレータを指定できます。
元:StringUtils.repeat("Hello"," ",2);
「ハローハロー」を返す
上記の例では、区切り文字としてスペースを使用して Hello 文字列を 2 回繰り返しています。3 番目の引数で n 回、2 番目の引数で任意のセパレーターを指定できます。
単純なループが仕事をします:
int n = 10;
String in = "foo";
String result = "";
for (int i = 0; i < n; ++i) {
result += in;
}
またはより大きな文字列またはより高い値の場合n
:
int n = 100;
String in = "foobarbaz";
// the parameter to StringBuilder is optional, but it's more optimal to tell it
// how much memory to preallocate for the string you're about to built with it.
StringBuilder b = new StringBuilder(n * in.length());
for (int i = 0; i < n; ++i) {
b.append(in);
}
String result = b.toString();