Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying strings

If you have a string for example:

String = "Hello world";

How do you get it to print out (n) times?

For example

System.out.print("Hello world" * 5);

to give the output:

Hello world
Hello world
Hello world
Hello world
Hello world

Now obviously I can't just multiply a string by 5, as I have done.

I know i have to convert the string into something an integer would be able to use? But how do I do this?

like image 455
hicks Avatar asked Nov 20 '25 01:11

hicks


2 Answers

You would use a loop:

for(int i = 0; i < 5; i++) {
   System.out.println("Hello world");
}

But I think you need to work on your programming fundamentals here - a good book on java would be much more useful to you than posting questions like this on SO.

like image 113
Eric Petroelje Avatar answered Nov 21 '25 13:11

Eric Petroelje


In Python (Ruby too I think) you can very much concatenate string by "multiplying" it by number:

>>> print "Hello" * 5
HelloHelloHelloHelloHello

In Java specifically there is quite a number of ways to do it, beginning with loop. Incidentally you can concatenate strings multiple times in Java:

package test;

public class test {

public static void main(String[] args) {

    String s1 = "hello";
    for (String s = s1; s.length() <= 5 * s1.length(); s = s + s1)
        System.out.println(s);
}

}

Now, above is a BAD IDEA. :-) If it is repeated, don't do it, bc every time you concatenate strings and assign a new one, a new string is created and old one is thrown away - very inefficient if you do it more than a few times.

In general, previous poster was right: pick a book about Java - better yet Python - and learn!

like image 21
mrkafk Avatar answered Nov 21 '25 13:11

mrkafk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!