главная продукты downloads форум тех. поддержка

 

Главная страница

Framework Tips Strings

FAQ Home

1. How to I introduce culture information into formatted strings?
2. How do I convert a string to an double or int?
3. How can I convert the string "Red" into the color Color.Red, and vice versa?
4. Is there a .Net way of deciding whether a string is numeric or not?
5. How can I determine if a string is a valid date?
6. How can I convert an Enumeration member to string and vice-versa?
7. My program dynamically builds lots of strings. Is there a way to optimize string performance?
8. I hate string processing. Is there an easier way to do string manipulation?
9. How do I use the CSV clipboard format supported by Excel?
10. Is there a easy way to test Regular Expressions?
 



1 How to I introduce culture information into formatted strings?

You use the CultureInfo class found in the System.Globalization namespace.

     DateTime dt = DateTime.Now;
     textBox2.Text = dt.ToString("D", new CultureInfo("de-DE"));
     textBox3.Text = dt.ToString("D", new CultureInfo("fr-FR"));
 



2 How do I convert a string to an double or int?

One way is to use static members of the Convert class in the System namespace.

          textBoxResult.Text = Convert.ToString(Convert.ToDouble(textBox1.Text) * Convert.ToDouble(textBox2.Text));
 



3 How can I convert the string "Red" into the color Color.Red, and vice versa?

You can use the TypeDescriptor class to handle this.

     Color redColor = (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString("Red");
     string redString = TypeDescriptor.GetConverter(typeof(Color)).ConvertToString(Color.Red);

You can also use code such as

    System.Drawing.ColorConverter ccv = new System.Drawing.ColorConverter();
     this.BackColor = (Color) ccv.ConvertFromString("Red");
 



4 Is there a .Net way of deciding whether a string is numeric or not?

VB.NET has a IsNumeric method that you can use to recognize a Short, Integer, Long, Decimal or Single numeric type. From C#, you can use try/catch to look for a particular numeric type.

     //long for a Single
     Single num;
     try
     {
          num = Single.Parse(someString);
     }
     catch (Exception e)
     {
          // if this is hit, someString is not a Single
     }
 



5 How can I determine if a string is a valid date?

You can use the static DateTime.Parse or DateTime.ParseExact and catch any exceptions.

     System.DateTime myDateTime;
     bool isValid = true;
     try
     {
          myDateTime = System.DateTime.Parse(strMyDateTime);
     }
     catch (Exception e)
     {
          isValid = false;
    }
 



6 How can I convert an Enumeration member to string and vice-versa?

To convert an enum to string, do this:

string enumEntryAsString = Enum.GetName(typeof(TabSizeMode), TabSizeMode.FillToRight);

To convert a string to an enum type:

// Enclose this code within try/catch.
TabSizeMode sizeMode = Enum.Parse(typeof(TabSizeMode), "1");

(or)

TabSizeMode sizeMode = Enum.Parse(typeof(TabSizeMode), "FillToRight");
 



7 My program dynamically builds lots of strings. Is there a way to optimize string performance?

Use the StringBuilder class to concatenate strings. This class reuses memory. If you add string members to concatenate them, there is extra overhead as new memory is allocated for the new string. If you do a series of concatenations using the strings (instead of StringBuilder objects) in a loop, you continually get new strings allocated. StringBuilder objects allocate a buffer, and reuse this buffer in its work, only allocating new space when the initial buffer is consumed. Here is a typical use case.

StreamReader sr = File.OpenText(dlg.FileName);
string s = sr.ReadLine();
StringBuilder sb = new StringBuilder();
while (s != null)
{
sb.Append(s);
s = sr.ReadLine();
}
sr.Close();
textBox1.Text = sb.ToString();
 



8 I hate string processing. Is there an easier way to do string manipulation?

.NET has excellent support for Regular Expressions. Get the excellent "Regular Expressions with .NET ", e-book by Dan Appleman. It has all that you need to get started.
Regular expressions really make string processing easier.


There are expressions that you can find on the web for everything from validating dates to phone numbers. There are several available at this site:
http://regxlib.com/
 



9 How do I use the CSV clipboard format supported by Excel?

In this case, the dataobject is a memory stream. Here are code snippets that allow you to get/set CSV values from/to the clipboard in a manner compatible with Excel.

[C#]
private void GetCSVFromClipBoard_Click(object sender, System.EventArgs e)
{
     IDataObject o = Clipboard.GetDataObject();
     if(o.GetDataPresent(DataFormats.CommaSeparatedValue))
     {
          StreamReader sr = new StreamReader((Stream) o.GetData(DataFormats.CommaSeparatedValue));
          string s = sr.ReadToEnd();
          sr.Close();
          Console.WriteLine(s);
     }
}

private void CopyCSVToClipBoard_Click(object sender, System.EventArgs e)
{
     String csv = "1,2,3" + Environment.NewLine + "6,8,3";
     byte[] blob = System.Text.Encoding.UTF8.GetBytes(csv);
     MemoryStream s = new MemoryStream(blob);
     DataObject data = new DataObject();
     data.SetData(DataFormats.CommaSeparatedValue, s);
     Clipboard.SetDataObject(data, true);
}

[VB.NET]
Private Sub GetCSVFromClipBoard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
     Dim o As IDataObject = Clipboard.GetDataObject()
     If Not o Is Nothing Then
          If (o.GetDataPresent(DataFormats.CommaSeparatedValue)) Then
               Dim sr As New StreamReader(CType(o.GetData(DataFormats.CommaSeparatedValue), Stream))
               Dim s As String = sr.ReadToEnd()
               sr.Close()
               Console.WriteLine(s)
          End If
     End If
End Sub 'GetCSVFromClipBoard_Click

Private Sub CopyCSVToClipBoard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
     Dim csv As String = "1,2,3" + Environment.NewLine + "6,8,3"
     Dim blob As Byte() = System.Text.Encoding.UTF8.GetBytes(csv)
     Dim s As New MemoryStream(blob)
     Dim data As New DataObject()
     data.SetData(DataFormats.CommaSeparatedValue, s)
     Clipboard.SetDataObject(data, True)
End Sub 'CopyCSVToClipBoard_Click
 



10 Is there a easy way to test Regular Expressions?

There are several tools that allow you to quickly test your regular expressions. Listed below are two that we use:

Expresso on CodeProject
RegexDesigner on SellsBrothers.com

 

e-mail:

 

bousoft@mail.ru