code

Java에서 문자열을 곱하여 시퀀스를 반복 할 수 있습니까?

codestyles 2020. 9. 18. 08:14
반응형

Java에서 문자열을 곱하여 시퀀스를 반복 할 수 있습니까? [복제]


이 질문에 이미 답변이 있습니다.

다음과 같은 것이 있습니다.

int i = 3;
String someNum = "123";

문자열에 i"0" 을 추가하고 싶습니다 someNum. 파이썬처럼 반복하기 위해 문자열을 곱할 수있는 방법이 있습니까?

그래서 그냥 갈 수 있습니다.

someNum = sumNum + ("0" * 3);

또는 비슷한 것?

이 경우 최종 결과는 다음과 같습니다.

"123000".


종속성이없는 일반 Java에서 가장 쉬운 방법은 다음과 같은 한 줄짜리입니다.

new String(new char[generation]).replace("\0", "-")

생성 을 반복 횟수로 바꾸고 "-"를 반복하려는 문자열 (또는 문자)로 바꿉니다 .

이 모든 작업은 n 개의 0x00 문자를 포함하는 빈 문자열을 만드는 것이며 , 내장 된 String # replace 메서드가 나머지를 수행합니다.

복사하여 붙여 넣을 수있는 샘플은 다음과 같습니다.

public static String repeat(int count, String with) {
    return new String(new char[count]).replace("\0", with);
}

public static String repeat(int count) {
    return repeat(count, " ");
}

public static void main(String[] args) {
    for (int n = 0; n < 10; n++) {
        System.out.println(repeat(n) + " Hello");
    }

    for (int n = 0; n < 10; n++) {
        System.out.println(repeat(n, ":-) ") + " Hello");
    }
}

아니요,하지만 Scala에서는 가능합니다! (그런 다음 컴파일하고 Java 구현을 사용하여 실행하십시오 !!!!)

이제 Java에서 쉽게 수행하려면 Apache commons-lang 패키지를 사용하십시오. maven을 사용한다고 가정하고 다음 종속성을 pom.xml에 추가하십시오.

    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.4</version>
    </dependency>

그리고 다음과 같이 StringUtils.repeat를 사용합니다.

import org.apache.commons.lang.StringUtils
...
someNum = sumNum + StringUtils.repeat("0", 3);

Google Guava 는 다음과 같은 다른 방법을 제공합니다 Strings#repeat().

String repeated = Strings.repeat("pete and re", 42);

두 가지 방법이 떠 오릅니다.

int i = 3;
String someNum = "123";

// Way 1:
char[] zeroes1 = new char[i];
Arrays.fill(zeroes1, '0');
String newNum1 = someNum + new String(zeroes1);
System.out.println(newNum1); // 123000

// Way 2:
String zeroes2 = String.format("%0" + i + "d", 0);
String newNum2 = someNum + zeroes2;
System.out.println(newNum2); // 123000

방법 2는 다음과 같이 줄일 수 있습니다.

someNum += String.format("%0" + i + "d", 0);
System.out.println(someNum); // 123000

자세한 내용 String#format()API 문서java.util.Formatter.


If you're repeating single characters like the OP, and the maximum number of repeats is not too high, then you could use a simple substring operation like this:

int i = 3;
String someNum = "123";
someNum += "00000000000000000000".substring(0, i);

No. Java does not have this feature. You'd have to create your String using a StringBuilder, and a loop of some sort.


Simple way of doing this.

private String repeatString(String s,int count){
    StringBuilder r = new StringBuilder();
    for (int i = 0; i < count; i++) {
        r.append(s);
    }
    return r.toString();
}

Java 8 provides a way (albeit a little clunky). As a method:

public static String repeat(String s, int n) {
    return Stream.generate(() -> s).limit(n).collect(Collectors.joining(""));
}

or less efficient, but nicer looking IMHO:

public static String repeat(String s, int n) {
    return Stream.generate(() -> s).limit(n).reduce((a, b) -> a + b);
}

with Dollar:

String s = "123" + $("0").repeat(3); // 123000

With Guava:

Joiner.on("").join(Collections.nCopies(i, someNum));

I don't believe Java natively provides this feature, although it would be nice. I write Perl code occasionally and the x operator in Perl comes in really handy for repeating strings!

However StringUtils in commons-lang provides this feature. The method is called repeat(). Your only other option is to build it manually using a loop.


No, you can't. However you can use this function to repeat a character.

public String repeat(char c, int times){
    StringBuffer b = new StringBuffer();

    for(int i=0;i &lt; times;i++){
        b.append(c);
    }

    return b.toString();
}

Disclaimer: I typed it here. Might have mistakes.


Using Java11(current in Early Access phase), you can achieve the same by using String.repeat API as follows :

int i = 3; //frequency to repeat
String someNum = "123"; // initial string
String ch = "0"; // character to append

someNum = someNum + ch.repeat(i); // formulation of the string
System.out.println(someNum); // would result in output -- "123000"

A generalisation of Dave Hartnoll's answer (I am mainly taking the concept ad absurdum, maybe don't use that in anything where you need speed). This allows one to fill the String up with i characters following a given pattern.

int i = 3;
String someNum = "123";
String pattern = "789";
someNum += "00000000000000000000".replaceAll("0",pattern).substring(0, i);

If you don't need a pattern but just any single character you can use that (it's a tad faster):

int i = 3;
String someNum = "123";
char c = "7";
someNum += "00000000000000000000".replaceAll("0",c).substring(0, i);

Similar to what has already been said:

public String multStuff(String first, String toAdd, int amount) { 
    String append = "";
    for (int i = 1; i <= amount; i++) {
        append += toAdd;               
    }
    return first + append;
}

Input multStuff("123", "0", 3);

Output "123000"


I created a method that do the same thing you want, feel free to try this:

public String repeat(String s, int count) {
    return count > 0 ? s + repeat(s, --count) : "";
}

we can create multiply strings using * in python but not in java you can use for loop in your case:

String sample="123";
for(int i=0;i<3;i++)
{
sample=+"0";
}

There's no shortcut for doing this in Java like the example you gave in Python.

You'd have to do this:

for (;i > 0; i--) {
    somenum = somenum + "0";
}

The simplest way is:

String someNum = "123000";
System.out.println(someNum);

참고URL : https://stackoverflow.com/questions/2255500/can-i-multiply-strings-in-java-to-repeat-sequences

반응형