java 字符串相乘
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14364076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiplying strings
提问by hicks
If you have a string for example:
例如,如果您有一个字符串:
String = "Hello world";
How do you get it to print out (n) times?
你如何让它打印出(n)次?
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.
现在显然我不能像我所做的那样将字符串乘以 5。
I know i have to convert the string into something an integer would be able to use? But how do I do this?
我知道我必须将字符串转换为整数可以使用的东西?但是我该怎么做呢?
回答by Eric Petroelje
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.
但我认为你需要在这里学习你的编程基础——一本关于 Java 的好书比在 SO 上发布这样的问题对你有用得多。
回答by mrkafk
In Python (Ruby too I think) you can very much concatenate string by "multiplying" it by number:
在 Python(我认为也是 Ruby)中,您可以通过将字符串“乘以”数字来非常多地连接字符串:
>>> 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:
特别是在 Java 中,有很多方法可以做到这一点,从循环开始。顺便说一句,您可以在 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.
现在,上面是一个坏主意。:-) 如果重复,请不要这样做,bc 每次连接字符串并分配一个新字符串时,都会创建一个新字符串并丢弃旧字符串-如果执行多次,效率会很低。
In general, previous poster was right: pick a book about Java - better yet Python - and learn!
总的来说,之前的海报是对的:选择一本关于 Java 的书——更好的是 Python——然后学习!
回答by Abubakkar
You can make a method that takes the string and the value for which the string needs to be printed like:
您可以创建一个方法来获取字符串和需要打印字符串的值,例如:
public String multiplyString(String s,int i){
String result="";
for(;i<0;i--){
result += " "+result; //for appending strings
}
return result;
}
Then call this method:
然后调用这个方法:
System.out.print(multiplyString("Hello wrold",5));
回答by someone
Hey learn bit on recursion method also
嘿,还学习了一些递归方法
public static void main(String[] args) throws IOException {
test("Hello World ",5);
}
public static void test(String s,int x){
if(x==0)return;
System.out.println(s);
test(s,--x);
}
Out put
输出
Hello World
Hello World
Hello World
Hello World
Hello World