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 / General / February 2006

Tip: Looking for answers? Try searching our database.

how to generate a random string

Thread view: 
Jacob - 22 Feb 2006 16:12 GMT
As an aid for unit testing I want to write a method
that generate a random string of a specified length:

  String getRandom(int length)
  {
     // magic
  }

My current approach is to generate n random bytes
and then convert them to a string using the String
ctor.

This *do* produce a string, but there are comments in
the String docs that worries me.

Is there more to this?

Thanks!
Thomas Fritsch - 22 Feb 2006 16:27 GMT
Jacob schrieb:

> As an aid for unit testing I want to write a method
> that generate a random string of a specified length:
[quoted text clipped - 5 lines]
>
> My current approach is to generate n random bytes
I would recommend the approach to generate n random *chars* (may be
restricted to the printable range from '\u0020' to '\u007E') and to make
a string from it using the String(char[]) constructor.

> and then convert them to a string using the String
> ctor.
To which of the many constructors
  String(byte[], ...)
do you refer here?

> This *do* produce a string, but there are comments in
> the String docs that worries me.
Which comment? (I'm not a mind-reader)

> Is there more to this?

Signature

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

Jacob - 22 Feb 2006 16:41 GMT
> I would recommend the approach to generate n random *chars* (may be
> restricted to the printable range from '\u0020' to '\u007E') and to make
> a string from it using the String(char[]) constructor.

And how do I make a random char?

Being "printable" is not an issue; I expect the most spectacular
errors are uncovered by the non-printable ones... :-)

> To which of the many constructors
>   String(byte[], ...)
> do you refer here?

String(byte[] bytes)

> Which comment? (I'm not a mind-reader)

The paragraph about the CharsetDecoder. jdk 1.5.0_06
Oliver Wong - 22 Feb 2006 16:43 GMT
>> I would recommend the approach to generate n random *chars* (may be
>> restricted to the printable range from '\u0020' to '\u007E') and to make
>> a string from it using the String(char[]) constructor.
>
> And how do I make a random char?

   You could generate an int within the valid range of char, and then do a
cast.

<code>
Random RNG = new Random();
char = (char)(RNG.nextInt(Character.MAX_VALUE + 1));
</code>

the +1 is because the upper bound is considered to be exclusive instead of
inclusive.

   - Oliver
steve - 23 Feb 2006 22:40 GMT
>> I would recommend the approach to generate n random *chars* (may be
>> restricted to the printable range from '\u0020' to '\u007E') and to make
[quoted text clipped - 14 lines]
>
> The paragraph about the CharsetDecoder. jdk 1.5.0_06

how long do they have to be?

short strings < 100 chars or biggy stuff 32k and the likes.

steve
Roedy Green - 24 Feb 2006 07:45 GMT
>And how do I make a random char?

see http://mindprod.com/jgloss/pseudorandom.html#LOWHIGH
to generate a random int in any given range. Just (char) cast the
result.

Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Chris Uppal - 22 Feb 2006 17:11 GMT
> My current approach is to generate n random bytes
> and then convert them to a string using the String
> ctor.

Generating random Strings by generating random bytes will get you into trouble.
Not all sequences of bytes correspond to legal encodings of character data
(depending on what character encoding you use).  Similarly not all sequences of
N bytes will decode to the same length String.

Why not generate random chars ?  They are numbers too, so you can generate them
just as easily as bytes.  Use a StringBuilder (or StringBuffer) to assemble
them into a String.

Generating strings of /readable/ characters takes a little more work, but not
much.

   -- chris
robert - 22 Feb 2006 20:32 GMT
> As an aid for unit testing I want to write a method
> that generate a random string of a specified length:
[quoted text clipped - 14 lines]
>
> Thanks!

Use java.util.UUID:

String getRandom(int length)  {
      // magic
       UUID uuid = UUID.randomUUID();
       String myRandom = uuid.toString()
          return myRandom.substring(length);
}

A UUID represents a 128-bit value. If you need more than that I suppose
just concat uuid's together.

HTH,
iksrazal
http://www.braziloutsource.com/
tom fredriksen - 22 Feb 2006 22:31 GMT
> As an aid for unit testing I want to write a method
> that generate a random string of a specified length:
[quoted text clipped - 3 lines]
>      // magic
>   }

For generating random numbers just use a random generator which you then
 cast to a char and add to a string. See Olivers example. You can for
example use a char array and add the array to a stringBuffer in a loop.

If you want random printable characters, then you create an array of all
legal characters starting form 0..N and take the random number modulo
the array length, that should give you a random printable character from
the array.

When it comes to whether the string needs or do not need to be
printable, I think you should think it through. Non printable characters
in a string can cause havoc if you are not prepared for it.

/tom
Stefan Ram - 22 Feb 2006 23:18 GMT
>As an aid for unit testing I want to write a method
>that generate a random string of a specified length:

 To find such a method, I look up my catalogue in the category

:catalogue:Treeg:programming:language/Java:libraries:string processing
http://purl.net/stefan_ram/garnoo/XOCATALOGUEXOYTREEGXOPROGRAMMINGXOLANGUAGEXSYJ
AVAXOLIBRARIESXOSTRINGXGPROCESSING


 The relevant (and only) entry is

http://nd-com.net/downloads/RandomString.java

 that shows how to get a random string matching a given regular
 expression.


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.