Advanced String Manipulation

  • Thread starter Thread starter Aaron
  • Start date Start date
A

Aaron

I like like to randomly output phone numbers seperated by \ and / from a string
s = "\231-3423/\453-1234/\231-3473/\231-3474/"


private string GetPhoneNum()
{
s = "\231-3423/\453-1234/\231-3473/\231-3474/"
//randomly pick a phone num from string.

n = randomNum;
return n;//ie. 453-1234
}

Thanks
 
Create (or create from your "/\" string) a string[] where each phone number
is in one element. Create your random numbers bounded from 0 -
(array.Length - 1), then just return that index of your string array.
 
Aaron

The string you've specified won't work because the escape sequence
won't be recognised unless you prefix the string literal with
@(verbatim).

string s = @"\231-3423/\453-1234/\231-3473/\231-3474/"

However, your delimiters are bizarre, why not just have single
characters rather then "/\" separating the data. Although you
probably have a very good reason for using those delimiters.

How about...

private static string GetPhoneNum()
{
Random r = new Random();
string phoneNumbers = "231-3423,453-1234,231-3473,231-3474";
string sep = ",";

string[] numbers = phoneNumbers.Split( sep.ToCharArray() );
return numbers[r.Next( 0, numbers.Length - 1 )];
}

HTH

Glenn
 
Kuya,

If you have the phone numbers hard coded, I would suggest the
following

string[] astrNumbers = {"231-3423", "453-1234", "231-3473",
"231-3474" }

Doing it this way will prevent from having to split the string before
selecting the random number. But if not, I would split the string
this way:

string strNumbers = @"\111-3423/\222-1234/\333-3473/\444-3474/";
string[] astrNumbers;
string strOut = "";
Random rndGenerator = new Random();
int intIndex;

// Remove the first and last chars
strNumbers = strNumbers.Remove( 0 , 1 );
strNumbers = strNumbers.Remove( strNumbers.Length - 1, 1 );

// Replace the double char delimiter with a single
strNumbers = strNumbers.Replace( @"/\", "," );

// Split the numbers into the array
astrNumbers = strNumbers.Split( new char[] { ',' } );

// Make sure you have at least one
if ( astrNumbers.Length > 0 )
{
// Using Next may not be random enough
// you may want to use the NextDouble till
// it's with in range of the array

// Randomly pick an array element
intIndex = rndGenerator.Next( astrNumbers.Length );

// Set the random element to return
strOut = astrNumbers[ intIndex ];
}

Console.WriteLine( "Number selected = " + strOut );

// Return the value
return strOut;

Hope this helps,
Glen Jones MCSD
 
Back
Top