Java >> How to create string of repeated characters?

by Roy Smith » Sat, 01 May 2004 21:08:39 GMT

What's the easiest way to create a String of 20 x's in Java? I know I
could do

String s = "xxxxxxxxxxxxxxxxxxxx";

but I don't want to count out 20 *'s (it's error prone and hard to
read). In python, I would just do

s = "x" * 20

is there a direct equivalent of that in Java? I've checked the
documentation for the Character, String, and StringBuffer classes but
don't see anything obvious.


Java >> How to create string of repeated characters?

by Martin Honnen » Sat, 01 May 2004 22:43:17 GMT







I guess you need to implement a method using a StringBuffer for that as in

public class Test20040501 {
public static String repeatChar (char character, int repeatCount) {
StringBuffer stringBuffer = new StringBuffer(repeatCount);
for (int i = 1; i <= repeatCount; i++) {
stringBuffer.append(character);
}
return stringBuffer.toString();
}

public static void main (String[] args) {
String x20 = repeatChar('x', 20);
System.out.println(x20 + "; " + x20.length());
String noX = repeatChar('x', 0);
System.out.println(noX + "; " + noX.length());
}

}
--

Martin Honnen
http://JavaScript.FAQTs.com/




Java >> How to create string of repeated characters?

by Daniel Sjlom » Sun, 02 May 2004 05:07:01 GMT




Heh. Java is not that high-level. You have to write it yourself. Maybe
something like:

import java.util.Arrays;

public static String repeat(char c, int len)
{
if (len < 0)
{
throw new IllegalArgumentException("Negative length");
}

char[] arr = new char[len];
Arrays.fill(arr, c);

return String.valueOf(arr);
}
--
Daniel Sjlom
Remove _NOSPAM to reply by mail


How to create string of repeated characters?

by Ben Wilson » Tue, 04 May 2004 04:58:00 GMT


"Roy Smith" < XXXX@XXXXX.COM > rote in messige



There is a simpler, and, in my mind, more elegant alternative, in which you
can avoid using a loop and must use only the String and StringBuffer
classes:

public static String repeatMaker(char token, int len)
{
StringBuffer sb1 = new StringBuffer("");
sb1.setLength(len);
return sb1.toString().replace('\u0000', token);
}

cheers,

Ben.




How to create string of repeated characters?

by Ben Wilson » Tue, 04 May 2004 14:08:44 GMT


"Roedy Green" < XXXX@XXXXX.COM > scritto in mesaj

you


Hello, Roedy.

I noticed that you replied to the OP, unfortunately I could not find the
actual code that you were referring to. You referred to some page from your
website, but when I clicked on the link
( http://mindprod.com/products.html #BUS) I feared I was in the wrong place.

Could you re-post your solution?

It is a firm belief of mine that the elegance of a solution increases
inverse proportional to the amount of nestings it requires to code and the
number of times the code departs from a fall-through, top-to-bottom sequence
of instructions that are in the natural reading order to which my
civilisation has grown accustomed. It is also a firm belief of mine that
elegance is not the same as performance.

As I understood it, elegance was the main concern of the OP. If performance
were his primary concern, I'm sure you'd agree he'd have been better off
writing String s = "xxxxxxxxxxxxxxxxxxxx".

You are of course right in pointing out that my reply was imprecise. Instead
of saying "avoid using a loop" I should have said "avoid coding a loop".

I hope you will have a chance to post your alternative.







How to create string of repeated characters?

by Daniel Sjlom » Tue, 04 May 2004 18:24:08 GMT




FWIW, I benchmarked the posted solutions (Ben's, Roedy's and my own)
with (running Sun JVM 1.4.2 on x86 linux):

public static void main(String[] args)
{

long time = System.currentTimeMillis();
String str = repeat('a', 10000000); // me
System.out.println("Me: " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
str = rep('a', 10000000); // roedy
System.out.println("Roedy: " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
str = repeatMaker('a', 10000000); // ben
System.out.println("Ben: " + (System.currentTimeMillis() - time));

}

Output average in ms(100 iterations):

Me: 290
Roedy: 730
Ben: 260

Another benchmark, this time with short strings and many calls:

public static void main(String[] args)
{
long roedy = 0, me = 0, ben = 0;

long time = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
{
String str = repeat('a', 18); // me
}
me += System.currentTimeMillis() - time;

time = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
{
String str = rep('a', 18); // roedy
}
roedy += System.currentTimeMillis() - time;

time = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
{
String str = repeatMaker('a', 18); // ben
}
ben += System.currentTimeMillis() - time;

System.out.println("Me: " + me);
System.out.println("Roedy: " + roedy);
System.out.println("Ben: " + ben);
}

Output:

Me: 492
Roedy: 1284
Ben: 1435
--
Daniel Sjlom
Remove _NOSPAM to reply by mail




How to create string of repeated characters?

by Roy Smith » Tue, 04 May 2004 19:45:47 GMT




Well, as the OP, I'm not sure "elegance" was what I was looking for.
More like simplicity. Simple to write, simple to understand, and
foolproof. My dislike of the string constant was that it was
error-prone to write (counting out all those *'s) and difficult to read.

I ended up with:

/*
* Generate a string of n stars. Used for creating
* test data for testClassify ().
*/
protected static String stars (int n)
{
StringBuffer buffer = new StringBuffer (n);
for (int i = 1; i <= n; i++) {
buffer.append ('*');
}
return buffer.toString();
}

The reason I needed this is for some unit tests of a data file parser
I'm writing. One of the lines in the file which delimits a section I
want to recognize is a string of *'s. I wrote a function which
classifies the line as the start of a header if it has 20 or more stars
on it. My unit tests look like this (doClassify is a thin wrapper
around assertEquals):

doClassify (parser.UNKNOWN, stars (19));
doClassify (parser.HEADER, stars (20));
doClassify (parser.HEADER, stars (21));
doClassify (parser.HEADER, stars (50));


How to create string of repeated characters?

by Thomas Schodt » Tue, 04 May 2004 22:39:38 GMT






If that was the concern, you could have done

String lotsOfAsterisks =
"************************" +
"************************" +
/* repeat ad nauseam */
"************************";

String star20 = String.substr(lotsOfAsterisks,0,20);
// etc.

Simple, and foolproof as long as lotsOfAsterisks is bigger than the
largest substring you require.


How to create string of repeated characters?

by Eric Sosman » Wed, 05 May 2004 00:11:48 GMT




Do you mean to tell me that all these high-falutin'
fancy-pants code-completin' auto-refactorin' buzzword-totin'
Aye Dee Ease still haven't discovered `^U 2 0 x'?

--
XXXX@XXXXX.COM


How to create string of repeated characters?

by Roy Smith » Wed, 05 May 2004 00:38:06 GMT

In article < XXXX@XXXXX.COM >,




I use emacs too, but just because I could do that, doesn't mean I think
it's the right way to code. Someday, somebody else is going to have to
read, maintain, or modify my code. Reading (and counting) a string of
20 x's isn't what humans are very good at.


How to create string of repeated characters?

by Roedy Green » Wed, 05 May 2004 01:52:39 GMT

On Tue, 04 May 2004 13:24:08 +0300, Daniel Sjlom
< XXXX@XXXXX.COM > wrote or quoted :


take off the intern if you want speed. The idea there was to avoid
polluting with many identical copies.

Canadian Mind Products, Roedy Green.
Coaching, problem solving, economical contract programming.
See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.


How to create string of repeated characters?

by Eric Sosman » Wed, 05 May 2004 01:53:41 GMT






Agreed. Humans should instead write a dozen or so lines
of Java code and spend time benchmarking the alternative
implementations. Anything less would be degrading, and only
an EOF (Extremely Old Fart) like myself would be willing to
accept such scut-work as actually pressing four keys.

Years ago I saw a posting that demonstrated the advance
of our understanding of programming by exhibiting the famous
"Hello, world!" program in several implementations. The first
fumbling effort was:

10 PRINT 'HELLO, WORLD!'

... which was obviously not the work of a trained Computer
Scientist. Succeeding examples followed the progress of this
newbie as his training advanced. I recall in particular a
pair of implementations showing increasing grasp of one language
much disparaged (with some cause) in this newsgroup:

main() {
printf ("Hello, world!\n");
}

transmogrified into

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
printf ("Hello, world!\n");
return EXIT_SUCCESS;
}

... as our knowledge-seeker graduated from C to Standard C.
Eventually, he wound up with about a hundred lines of C++, full
of constructors, destructors, instructors, exceptions, deceptions,
utility classes, futility classes, methods, virtual methods,
imaginary methods, friendly members, private parts, templates,
and toe-plates. And it would print "Hello, world!" *almost*
every time.

See also

http://www.netspace.org/ ~dmacks/pub/comp/eternal-donuts

--
XXXX@XXXXX.COM


How to create string of repeated characters?

by Grant Wagner » Fri, 07 May 2004 23:20:38 GMT






Very similar to:

String.prototype.repeat(n) {
return (new Array(n - 1)).join(this);
}
alert("x".repeat(10));

in Javascript.

I like your solution, timing tests later in this thread clearly show it to
be one of, if not the, fastest, and most elegant (in my opinion) solution. I
thought the point of class libraries and existing methods is to leverage
that code and not reinvent the wheel, but when it comes to something like
building a fixed length string of a single character, everyone seems to love
coding them thar loops instead of taking advantage of the fact that there
are methods that already do that for them.

| Grant Wagner < XXXX@XXXXX.COM >



How to create string of repeated characters?

by Boudewijn Dijkstra » Sun, 06 Jun 2004 20:17:56 GMT

"Roy Smith" < XXXX@XXXXX.COM > schreef in bericht




Counting is hardly necessary when using editor which can show you what
column the cursor is currently on. Most Java-developing humans are
perfectly capable of placing the cursor on the start and end of the x's,
subtracting the column values and comparing with 20.




How to create string of repeated characters?

by Alex Hunsley » Sun, 06 Jun 2004 22:49:08 GMT







Irrelevant. As soon as code readability starts depending on features of
the editor you're using (or not using), it's bad practise.




Similar Threads

1. Java equivalent to VB 'string' function (create string with repeating characters)?

Hi,

Is there an equivalent in Java to the VB 'string' function, which
creates a string of 'x' repeating characters?

For instance, something like:

String s = vbEquivString("x", 6);	// yields s = "xxxxxx"

Thanks,
Jim

2. Java equivalent to VB 'string' function (create string with repeating characters)? - Java

3. A string composed of a character repeated x number of times

In Java, what function/method do we have for constructing composed of
a single character repeated x number of times.

I am looking for the .NET equivalant of this String class constructor:

public String(char c, int numTimesToRepeat);

I looked at the java.lang.String class' constructors and couldn't find
one that matched my needs.

4. Create a string with (n) copies of the same character

5. Character Repeat

I'm looking for an easy way to repeat a character.

For example in Perl if you want 5 "x"'s the code is
$str = "x" x 5;  # result xxxxx

I've tried a few ways in javascript to accomplish this, but can not
come up with anything other then the lame old basic way which is
probably more processing then required...

var str = "";
for (var i = 0; 5 > i; i++){
  str += "x";
}

Any better solutions?

6. Javascript: filter repeating character...

7. adding characters like character 253, 254 to javascript strings

Hi,

Convert the character to hex and build the string as:

str = '\xFD\xFE';

as \xHEXCODEHERE

regards,
Elias


8. XSLT - String manipulation character by character - Java