Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / January 2005

Tip: Looking for answers? Try searching our database.

Easiest way to create a string with n times character 'x'?

Thread view: 
Arnold Peters - 27 Jan 2005 19:34 GMT
Assume I want to create a string of length n which contains n times the character 'x'.
How do I implement this the easiest way? n could vary from function time to time.

Ok. I could code

char mychar = 'x';
String tmp = "";
for (int i=1; i<n; i++)
   tmp = tmp + String(mychar);
   
But this is very (!) inefficient.

Other solution would be:

String ressource = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
String tmp = ressource.subsctring(0,n);

But this is inefficient too and requires a a priori determination of the maximum possible
length;

As far as I know there is a function similar to

String tmp = makeString('x',n);

but I don't remember the exact name.
Can somehelp give me a hint?

Arni
Heiner K?cker - 27 Jan 2005 20:14 GMT
> Assume I want to create a string of length n which contains n times the character 'x'.
> How do I implement this the easiest way? n could vary from function time to time.
[quoted text clipped - 24 lines]
>
> Arni

StringBuffer.append is faster than string += ...

It saved garbage collector work.

StringBuffer strBuff = new StringBuffer(n);
for (int i=1; i<n; i++)
 strBuff.appen(mychar);

String result = StrBuff.toString();

Signature

Heiner Kuecker
Internet: http://www.heinerkuecker.de  http://www.heiner-kuecker.de
JSP WorkFlow PageFlow Page Flow FlowControl Navigation: http://www.control-and-command.de
Java Expression Formula Parser: http://www.heinerkuecker.de/Expression.html
CnC Template Technology http://www.heinerkuecker.de/Expression.html#templ
Domain Specific Languages http://www.heinerkuecker.de/DomainParser.html

Rhino - 27 Jan 2005 20:28 GMT
> Assume I want to create a string of length n which contains n times the character 'x'.
> How do I implement this the easiest way? n could vary from function time to time.
[quoted text clipped - 22 lines]
> but I don't remember the exact name.
> Can somehelp give me a hint?

I'm not aware of any existing method that does what you're asking. (That
doesn't mean there is no such method, just that I don't know about it.)
However, I needed a method that did what you're talking about a couple of
years ago and wrote this static method within a class called Miscellaneous:
----------------------------------------------------------------------------
--------------------
/**
* Method copies() concatenates an input String to itself specified number
of times.
*
* @param input any String that needs to be duplicated
* @param numCopies the number of copies of the input which need to be
concatenated
* @return the input String concatenated to itself numCopies times
*/
public static String copies(String input, int numCopies) {

StringBuffer myDup = new StringBuffer();
for (int ix=0; ix<numCopies; ix++) {
 myDup.append(input);
 }

return(myDup.toString());
}

----------------------------------------------------------------------------
--------------------

To invoke it:
----------------------------------------------------------------------------
--------------------
/* Test method to concatenate a String to itself a specified number of
times. */
String myInput = "Foo";
int myCopies = 3;
System.out.println("  The string, " + myInput + ", duplicated " + myCopies
+ " times is: " + Miscellaneous.copies(myInput, myCopies));

----------------------------------------------------------------------------
--------------------

I don't claim that this is the easiest or most efficient way of doing the
job but it certainly seems simple to me. It might serve your needs just the
way it is or be the basis of your own solution.

Rhino
mprudhom - 27 Jan 2005 20:34 GMT
Something like this is the most terse way to do it, and it much faster
than String concatenation:

char[] c = new char[mysize];
java.util.Arrays.fill (c, 'x');
String str = new String (c);
Joona I Palaste - 27 Jan 2005 20:42 GMT
Arnold Peters <apet10@hotmail.com> scribbled the following
on comp.lang.java.programmer:
> Assume I want to create a string of length n which contains n times the character 'x'.
> How do I implement this the easiest way? n could vary from function time to time.

> Ok. I could code

> char mychar = 'x';
> String tmp = "";
> for (int i=1; i<n; i++)
>     tmp = tmp + String(mychar);
>    
> But this is very (!) inefficient.

> Other solution would be:

> String ressource = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
> String tmp = ressource.subsctring(0,n);

> But this is inefficient too and requires a a priori determination of the maximum possible
> length;

> As far as I know there is a function similar to

> String tmp = makeString('x',n);

> but I don't remember the exact name.
> Can somehelp give me a hint?

A slightly varied solution from your first one.
StringBuffer buf = new StringBuffer();
for (int i=1; i<n; i++) {
 buf.append(mychar);
}
tmp = buf.toString();
This does pretty much the same thing as your first solution but skips
the creating of intermediary String objects. Should be at least twice
as efficient.

Signature

/-- Joona Palaste (palaste@cc.helsinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"This is a personnel commuter."
  - Train driver in Scientific American

Thomas Kellerer - 27 Jan 2005 20:52 GMT
Joona I Palaste wrote on 27.01.2005 21:42:
> A slightly varied solution from your first one.
> StringBuffer buf = new StringBuffer();
[quoted text clipped - 5 lines]
> the creating of intermediary String objects. Should be at least twice
> as efficient.
Even faster (because it's not synchronized:

char[] buffer = new char[size];
for (int i=0; i < size; i++)
{
    buffer[i] = c;
}
tmp = new String(buffer);
Thomas Fritsch - 28 Jan 2005 17:23 GMT
> Joona I Palaste wrote on 27.01.2005 21:42:
>
[quoted text clipped - 16 lines]
> }
> tmp = new String(buffer);

Even easier, and as fast as the above:

char[] buffer = new char[size];
Arrays.fill(buffer, c);
tmp = new String(buffer);

Signature

"Thomas:Fritsch$ops:de".replace(':','.').replace('$','@')

gimme_this_gimme_that@yahoo.com - 28 Jan 2005 03:52 GMT
StringBuffer buf = new StringBuffer(n); // Note the n

> A slightly varied solution from your first one.
> StringBuffer buf = new StringBuffer();
[quoted text clipped - 11 lines]
> "This is a personnel commuter."
>    - Train driver in Scientific American
Fred - 28 Jan 2005 05:35 GMT
char[] buffer = new char[size];
Doing this also suffers from the need to know the maxmium size of the
string beforehand.

The StringBuffer solution above would work without needing this
information. Additionally, an enhancing modification would be:

StringBuffer buf = new StringBuffer();
synchronized( buf ) {
for (int i=1; i<n; i++) {
buf.append(mychar);
}
}

This would eliminate the need to capture the lock on "buf" everytime
.append() is called.

If this procedure does not have to be synchronized (or guaranteed to be
thread safe), investigate using the StringBuilder class.  This requires
Java 1.5 but will not introduce the synchronization overhead of the
StringBuffer class.
Thomas Kellerer - 28 Jan 2005 07:56 GMT
> char[] buffer = new char[size];
> Doing this also suffers from the need to know the maxmium size of the
> string beforehand.

Why?

StringBuffer buf = new StringBuffer();
synchronized( buf ) {
for (int i=1; i<n; i++) {
buf.append(mychar);
}
}

The usage of n here is exactly the same as with new char[n] I cannot see a
difference.

I find the usage of the synchronized keyword there interesting. Are you saying
that the JVM will not synchronize the call to append() if it's called in a
synchronized block?

Regards
Thomas
Jesper Nordenberg - 28 Jan 2005 12:34 GMT
> I find the usage of the synchronized keyword there interesting. Are you saying
> that the JVM will not synchronize the call to append() if it's called in a
> synchronized block?

If the append() method synchronizes on the StringBuffer object (which
I believe it does) there would be some gains if it's faster to check a
lock you already have than to acquire and release it, and the Hotspot
compiler doesn't eliminate the lock/unlock code completely because the
StringBuffer object never escapes the method and therefore can't be
accessed by other threads.

/Jesper Nordenberg
Thomas Kellerer - 28 Jan 2005 12:51 GMT
>>char[] buffer = new char[size];
>>Doing this also suffers from the need to know the maxmium size of the
>>string beforehand.

I did some timings on the different solutions using the following program

public class Test
{
 public static String fillString1(int size, char c)
 {
   StringBuffer b = new StringBuffer(size);
   for (int i=0; i < size; i++)
   {
     b.append(c);
   }
   return b.toString();
 }

 public static String fillString2(int size, char c)
 {
   StringBuffer b = new StringBuffer(size);
   synchronized (b)
   {
     for (int i=0; i < size; i++)
     {
       b.append(c);
     }
   }
   return b.toString();
 }

 public static String fillString3(int size, char c)
 {
   char[] b = new char[size];
   for (int i=0; i < size; i++)
   {
     b[i] = c;
   }
   return new String(b);
 }

 public static void main(String[] args)
 {
   long start, end;
   int count = 500000;
   int size = 50;
   char c = 'x';

   start = System.currentTimeMillis();
   for (int i=0; i < count; i++)
   {
     String s = fillString1(size, c);
   }
   end = System.currentTimeMillis();
   System.out.println("time1: " + (end - start));

   start = System.currentTimeMillis();
   for (int i=0; i < count; i++)
   {
     String s = fillString2(size, c);
   }
   end = System.currentTimeMillis();
   System.out.println("time2: " + (end - start));

   start = System.currentTimeMillis();
   for (int i=0; i < count; i++)
   {
     String s = fillString3(size, c);
   }
   end = System.currentTimeMillis();
   System.out.println("time3: " + (end - start));
 }
}

On my computer the version with the char[] is significantly faster then the
StringBuffer version:

time1: 1953
time2: 1462
time3: 330

It doesn't change too much when increasing the size of the generated string
(simply play around with the size parameter)

So the synchronization trick actually shows some performance gain.

Regards
Thomas
Chris Uppal - 28 Jan 2005 15:19 GMT
> So the synchronization trick actually shows some performance gain.

Interesting.  Which JVM do your numbers apply to ?

   -- chris
Thomas Kellerer - 28 Jan 2005 15:44 GMT
>>So the synchronization trick actually shows some performance gain.
>
> Interesting.  Which JVM do your numbers apply to ?

Running on Windows XP:

Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_06-b03)
Java HotSpot(TM) Client VM (build 1.4.2_06-b03, mixed mode)

The timing with Sun's JDK 1.5.0 is nearly the same.

Thomas
Fred - 28 Jan 2005 16:23 GMT
> > char[] buffer = new char[size];
> > Doing this also suffers from the need to know the maxmium size of the
[quoted text clipped - 18 lines]
> Regards
> Thomas

> > char[] buffer = new char[size];
> > Doing this also suffers from the need to know the maxmium size of the
> > string beforehand.
>
> Why?

Because the value of "size" isn't going to be assigned
nondeterministically.
anonymous - 27 Jan 2005 21:58 GMT
> Assume I want to create a string of length n which contains n times the character 'x'.
> How do I implement this the easiest way? n could vary from function time to time.
[quoted text clipped - 24 lines]
>
> Arni

I think it might be more efficient to create a byte array and use it
with one of the gazillion String xtors?


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.