Skip to content
1

Random Unicode-Compatible String Generation

Here’s a quick snippet of code that will generate random unicode-compatible strings in C++:

const wchar_t *stringtable = L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

const wchar_t *RandomString( int length )
{
    wchar_t    *randomstring = new wchar_t[length];
    wmemset( randomstring, 0, sizeof( randomstring ) );
    for( int i = 0; i < length; i++ )
    {
        wmemcpy( randomstring + i, &stringtable[rand()%wcslen(stringtable)], 1 );
    }

    wmemset( randomstring + length, 0, wcslen(randomstring) – length );
    return randomstring;
}

I believe the only header you need to include is <stdlib.h>. I’m using this inside of a program I’ve written so it includes a bunch of headers. If <stdlib.h> alone doesn’t work, use <Windows.h> as well. I’m not sure what the equivalent include would be in Linux if <stdlib.h> alone doesn’t work.

1 Comment Post a comment
  1. Dec 23 2008

    Yeah, it doesn’t generate Unicode strings, but it is compatible if whatever you’re trying to send them to only accepts std::wstring or wchar_t.

    Just figured I’d put a little note about that in there so I don’t look like a total dumbass.

    Reply

Share your thoughts, post a comment.

(required)
(required)

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments

Get Adobe Flash playerPlugin by wpburn.com wordpress themes