Populate Array

  • Thread starter Thread starter Anil
  • Start date Start date
A

Anil

Hi All,

I have a string which has product names, which are seperated by comma. The
number of products in the string are random.
I want to populate the array using the string, one product per level.

Please let me know how to do it.

Thanks in Advance,
Anil
 
Anil,

Try this out.

// generate a random comma-delimited string for your product names
const string randChars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random r = new Random();

const string delimiters = ","; // characters that count as delimiters
int maxNames = 10; // maximum number of random names to generate
int maxLength = 32; // maximum length of characters in random name string

System.Text.StringBuilder sb = new System.Text.StringBuilder();

// O(maxNames * maxLength) loop to generate names
for (int i = 0; i < r.Next(maxNames+1); i++)
{
// generate a name by picking one character at a time
for (int j = 0; j < r.Next(maxLength+1); j++)
{
// append a random alphabetic character to the end of the current name
sb.Append(randChars.Substring(r.Next(randChars.Length), 1));
}
// append a random delimiter character to the end and start a new name
sb.Append(delimiters.Substring(r.Next(delimiters.Length), 1));
}

// get the product names into a string array
string[] prodNames = sb.ToString().Split(delimiters.ToCharArray());

// print the product names
foreach (string s in prodNames)
{
Console.WriteLine("Product name found: {0}", s);
}
I have a string which has product names, which are seperated by comma. The
number of products in the string are random.

You can see that the number of products is indeterminate at compile-time
(it's random!), so this solution should work in general if you want to test
the Split method out on random product names. The Split method is what you
want to use here to get the individual strings.

Best wishes,
JJ Feminella
 
Back
Top