This question already has answers here:
How can I generate random alphanumeric strings?
(36 answers)
Closed 8 years ago.
I have a method which generates the Coupon Code. Can anyone help/ suggest to generate ALPHANUMERIC CODE?
Following is the method:
public string CouponGenerator(int length)
{
var sb = new StringBuilder();
for (var i = 0; i < length; i++)
{
var ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * _random.NextDouble() + 65)));
sb.Append(ch);
}
return sb.ToString();
}
private static readonly Random _random = new Random();
Example:
UZWKXQML when Lenght is set to 8
But it need something like U6WK8Q2L i.e Alphanumeric code.
You can change the length of Coupan code.
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var random = new Random();
var result = new string(
Enumerable.Repeat(chars, 8)
.Select(s => s[random.Next(s.Length)])
.ToArray());
Just shuffle sequency of alpha bet and take number of chars that you need.
public string CouponGenerator(int length, char[] alphaNumSeed)
{
var coupon = alphaNumSeed.OrderBy(o => Guid.NewGuid()).Take(length);
return new string(coupon.ToArray());
}
Related
This question already has answers here:
Splitting a string into chunks of a certain size
(39 answers)
Closed 3 years ago.
What's the most efficient way to split string values into an array every specified number of times? For example, split by 2:
string test = "12345678";
To:
string[] test = new[] {"12", "34", "56"};
What I've tried:
double part = 2;
int k = 0;
var test = bin.ToLookup(c => Math.Floor(k++ / part)).Select(e => new string(e.ToArray()));
You can use LINQ : when length was the length of part
var str = "12345678";
var length = 2;
var result = Enumerable.Range(0, (str.Length + length - 1) / length)
.Select(i => str.Substring(i * length, Math.Min(str.Length - i *length,
length)));
This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 7 years ago.
I'm trying to create a scrubbing program and I'm stuck on a bit where I have to generate a set of random numbers to replace a string of numbers and while I can get the random number once, I can't seem to figure out how to make it replace the entire nine character string.
public static int GetRandomNumber()
{
Random rnd = new Random();
// creates a number between 0 and 9
int ranNum = rnd.Next(10);
return ranNum;
}
I know it has something to do with checking against the string length and repeating until it replaces the entire string but I can't for the life of me remember how and googling is a bit too non-specific. The string itself is being pulled from a text file and has been split into an array.
public static string[] ScrubData(string line)
{
string[] words = line.Split('|');
replaceData(words);
MessageBox.Show(words[0] + words[2]);
return words;
}
private static void replaceData(string[] words)
{
words[0] = Convert.ToString(GetRandomNumber());
}
I know someone already asked a similar question, but I have no idea what "lock" is or how to connect their question with mine.
Not sure I completely understood, but it sounds like you want a method that returns a string of random numbers that is the same length as th input string? If so, this should work:
private static Random _rnd = new Random();
public static string ReplaceCharactersWithRandomNumbers(string input)
{
if (input == null) return null;
var newString = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
newString.Append(_rnd.Next(10));
}
return newString.ToString();
}
Update
I modified the code to initialize the Random outside the method. This will ensure unique numbers each time you call it. If the object is initialized in the method, it may get seeded with the same value each time it's called, and will generate the same numbers each time.
If you want to be tricky, here's a one-line way to do it:
private static readonly Random Rnd = new Random();
public static string ReplaceCharactersWithRandomNumbers(string input)
{
return input == null ? null : string.Join("", input.Select(c => Rnd.Next(10)));
}
You need to enumerate the string and rebuild the entire string. It looks like your input string is a set of tokens separated with tee ("|") marks. I use the StringBuilder because concatenation of a lot of strings is slow in .NET.
Try this ... or something similar:
public static string ScrubData(string line)
{
string[] words = line.Split('|');
System.Text.StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.Length; i++)
{
sb.Append(GetRandomNumber().ToString());
if (i + 1 < words.Length)
sb.Append("|");
}
return sb.ToString();
}
This question already has answers here:
Splitting a string into chunks of a certain size
(39 answers)
Split string after certain character count
(4 answers)
Closed 8 years ago.
I have a text file with various 16 char strings both appended to one another and on separate lines. I've done this
FileInfo f = new FileInfo("d:\\test.txt");
string FilePath = ("d:\\test.txt");
string FileText = new System.IO.StreamReader(FilePath).ReadToEnd().Replace("\r\n", "");
CharCount = FileText.Length;
To remove all of the new lines and create one massively appended string. I need now to split this massive string into an array. I need to split it up on the consecutive 16th char until the end. Can anyone guide me in the right direction? I've taken a look at various methods in String such as Split and in StreamReader but am confused as to what the best way to go about it would be. I'm sure it's simple but I can't figure it out.
Thank you.
Adapting the answer from here:
You could try something like so:
string longstr = "thisisaverylongstringveryveryveryveryverythisisaverylongstringveryveryveryveryvery";
IEnumerable<string> splitString = Regex.Split(longstr, "(.{16})").Where(s => s != String.Empty);
foreach (string str in splitString)
{
System.Console.WriteLine(str);
}
Yields:
thisisaverylongs
tringveryveryver
yveryverythisisa
verylongstringve
ryveryveryveryve
ry
One possible solution could look like this (extracted as extension method and made dynamic, in case different token size is needed and no hard-coded dependencies):
public static class ProjectExtensions
{
public static String[] Chunkify(this String input, int chunkSize = 16)
{
// result
var output = new List<String>();
// temp helper
var chunk = String.Empty;
long counter = 0;
// tokenize to 16 chars
input.ToCharArray().ToList().ForEach(ch =>
{
counter++;
chunk += ch;
if ((counter % chunkSize) == 0)
{
output.Add(chunk);
chunk = String.Empty;
}
});
// add the rest
output.Add(chunk);
return output.ToArray();
}
}
The standard usage (16 chars) looks like this:
// 3 inputs x 16 characters and 1 x 10 characters
var input = #"1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890";
foreach (var chunk in input.Chunkify())
{
Console.WriteLine(chunk);
}
The output is:
1234567890ABCDEF
1234567890ABCDEF
1234567890ABCDEF
1234567890
Usage with different token size:
foreach (var chunk in input.Chunkify(13))
{
Console.WriteLine(chunk);
}
and the corresponding output:
1234567890ABC
DEF1234567890
ABCDEF1234567
890ABCDEF1234
567890
It is not a fancy solution (and could propably be optimised for speed), but it works and it is easy to understand and implement.
Create a list to hold your tokens. Then get subsequent substrings of length 16 and add them to the list.
List<string> tokens = new List<string>();
for(int i=0; i+16<=FileText.Length; i+=16) {
tokens.Add(FileText.Substring(i,16));
}
As mentioned in the comments, this ignores the last token if it has less than 16 characters. If you want it anyway you can write:
List<string> tokens = new List<string>();
for(int i=0; i<FileText.Length; i+=16) {
int len = Math.Min(16, FileText.Length-i));
tokens.Add(FileText.Substring(i,len);
}
Please try this method. I haven't tried it , but used it once.
int CharCount = FileText.Length;
int arrayhold = (CharCount/16)+2;
int count=0;
string[] array = new string[arrayhold];
for(int i=0; i<FileText.Length; i+=16)
{
int currentleft = FileText.Length-(16*count);
if(currentleft>16)
{
array[count]=FileText.Substring(i,16);
}
if(currentleft<16)
{
array[count]=FileText.Substring(i,currentleft);
}
count++;
}
This is the new code and provide a TRUE leftovers handling. Tested in ideone
Hope it works
Try this one:
var testArray = "sdfsdfjshdfalkjsdfhalsdkfjhalsdkfjhasldkjfhasldkfjhasdflkjhasdlfkjhasdlfkjhasdlfkjhasldfkjhalsjfdkhklahjsf";
var i = 0;
var query = from s in testArray
let num = i++
group s by num / 16 into g
select new {Value = new string(g.ToArray())};
var result = query.Select(x => x.Value).ToList();
result is List containing all the 16 char strings.
I'm trying to generate a 16 chars random string with NO DUPLICATE CHARS. I thoght that it shouldn't be to hard but I'm stuck.
I'm using 2 methods, one to generate key and another to remove duplicate chars. In main I've created a while loop to make sure that generated string is 16 chars long.
There is something wrong with my logic because it just shoots up 16-char string
with duplicates. Just can't get it right.
The code:
public string RemoveDuplicates(string s)
{
string newString = string.Empty;
List<char> found = new List<char>();
foreach (char c in s)
{
if (found.Contains(c))
continue;
newString += c.ToString();
found.Add(c);
}
return newString;
}
public static string GetUniqueKey(int maxSize)
{
char[] chars = new char[62];
chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data);
data = new byte[maxSize];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(maxSize);
foreach (byte b in data)
{
result.Append(chars[b % (chars.Length)]);
}
return result.ToString();
}
string builder = "";
do
{
builder = GetUniqueKey(16);
RemoveDuplicates(builder);
lblDir.Text = builder;
Application.DoEvents();
} while (builder.Length != 16);
Consider implementing shuffle algorithm with which you will shuffle your string with unique characters and then just pick up first 16 characters.
You can do this in-place, by allocating single StringBuffer which will contain your initial data ("abc....") and just use Durstenfeld's version of the algorithm to mutate your buffer, than return first 16 chars.
There are many algorithms for this.
One easy one is:
Fill an array of chars with the available chars.
Shuffle the array.
Take the first N items (where N is the number of characters you need).
Sample code:
using System;
namespace ConsoleApplication2
{
internal class Program
{
private static void Main(string[] args)
{
var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
Random rng = new Random();
for (int i = 0; i < 10; ++i)
{
string randomString = RandomString(16, chars, rng);
Console.WriteLine(randomString);
}
}
public static string RandomString(int n, char[] chars, Random rng)
{
Shuffle(chars, rng);
return new string(chars, 0, n);
}
public static void Shuffle(char[] array, Random rng)
{
for (int n = array.Length; n > 1; )
{
int k = rng.Next(n);
--n;
char temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
}
}
const string chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
var r = new Random();
var s = new string(chars.OrderBy(x => r.Next()).Take(16).ToArray());
I am using a GUID generation method it itself generates random strings and you can modify it if a number appears in the beginning,
use the code given below:
string guid = System.Guid.NewGuid().ToString("N");
while (char.IsDigit(guid[0]))
guid = System.Guid.NewGuid().ToString("N");
Hope that helps.
See if this helps:
RandomString()
{
string randomStr = Guid.NewGuid().ToString();
randomStr = randomStr.Replace("-", "").Substring(0, 16);
Console.WriteLine(randomStr);
}
This returns alpha-numeric string.
I am working on a requirement to randomly generate codes(like a random number). The code should be a alphanumeric but should only allow (A-Z0-9]. The user can specify the number of characters in the code. The code can be 4-9 chars long depending on the user input.
an example of the code would be 'AG43', 'XFR4A5UU0'.
Edit :- I am looking at the best way to solve this. I was looking at generating 2 digit random number in the range 11 to 99. If the number is between 65 & 90 (ascii of A-z ), I will use the ascii for it else i will append the number generated to my code string.
Please advise.
var number_of_chars = 4;
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var random = new Random();
var result = new string(
Enumerable.Repeat(chars, number_of_chars)
.Select(s => s[random.Next(s.Length)])
.ToArray());
public string GetRandomString(int length)
{
var newBuffer = new byte[length];
if (length <= 0)
return null;
// This was used for a password generator... change this how every needed
var charSet = ("ABCDEFGHJKLMNPQRSTUVWXYZ" +
"abcdefghijkmnprstuvxyz" +
"23456789").ToCharArray();
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(newBuffer);
var newChars = newBuffer.Select(b => charSet[b % charSet.Length]).ToArray();
return new string(newChars);
}
}