How to Multiply Strings in Java to Repeat Sequences

Java String Multiplication

How about this??

System.out.println(String.format("%10s", "").replace(' ', '*'));

This gives me output as **********.

I believe this is what you want...

Update 1

int yournumber = 10;
System.out.println(String.format("%" + yournumber + "s","*").replace(' ', '*'));

Good Luck!!!

Simple way to repeat a string

String::repeat

". ".repeat(7)  // Seven period-with-space pairs: . . . . . . . 

New in Java 11 is the method String::repeat that does exactly what you asked for:

String str = "abc";
String repeated = str.repeat(3);
repeated.equals("abcabcabc");

Its Javadoc says:

/**
* Returns a string whose value is the concatenation of this
* string repeated {@code count} times.
* <p>
* If this string is empty or count is zero then the empty
* string is returned.
*
* @param count number of times to repeat
*
* @return A string composed of this string repeated
* {@code count} times or the empty string if this
* string is empty or count is zero
*
* @throws IllegalArgumentException if the {@code count} is
* negative.
*
* @since 11
*/

Simple way to repeat a string

String::repeat

". ".repeat(7)  // Seven period-with-space pairs: . . . . . . . 

New in Java 11 is the method String::repeat that does exactly what you asked for:

String str = "abc";
String repeated = str.repeat(3);
repeated.equals("abcabcabc");

Its Javadoc says:

/**
* Returns a string whose value is the concatenation of this
* string repeated {@code count} times.
* <p>
* If this string is empty or count is zero then the empty
* string is returned.
*
* @param count number of times to repeat
*
* @return A string composed of this string repeated
* {@code count} times or the empty string if this
* string is empty or count is zero
*
* @throws IllegalArgumentException if the {@code count} is
* negative.
*
* @since 11
*/

Print a String 'X' Times (No Loop)

You can use recursion like this

private void printStar(int n){
if(n > 0){
System.out.print("*");
printStar(n-1);
}
}

And call the method like this initially - printStar(4);



Related Topics



Leave a reply



Submit