We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › How to Fill a String
Page Index Toggle Pages: 1
How to Fill a String? (Read 590 times)
How to Fill a String?
Aug 26th, 2007, 4:19am
 
int n=5;  char c='-';  How to make a string of n c's ?

Of course I can do:  String s="-----";

But generally? Is there a better way than this:

String s="";
for (int i=0;i<n;i++) s=s+c;

Re: How to Fill a String?
Reply #1 - Aug 26th, 2007, 1:11pm
 
Hi, you should know that Strings are final, meaning that everytime you want to change a string Java internally creates a new stringobject with the new value and rereferences the new string with the original string name, thus adding the original instance to the garbage collector.

IMHO the better and faster way would be to use the StringBuffer Class.

Code:

void setup(){
String s;
StringBuffer sb = new StringBuffer(1000);
for (int i=0; i< 1000; i++){
sb.append("x");
}
s = sb.toString();
println(s);
}


Here's a read for more information:

http://java.sun.com/j2se/1.3/docs/api/java/lang/StringBuffer.html
Re: How to Fill a String?
Reply #2 - Aug 26th, 2007, 9:54pm
 
though if you're using chars, append('-') will be more efficient than append("-").

for a couple letters this works fine.. if you need a thousand of them, you might be better off using the java method Arrays.fill(). to create a big char[] array, and then calling "new String()" on that.
Page Index Toggle Pages: 1