Showing posts with label String Manipulation. Show all posts
Showing posts with label String Manipulation. Show all posts

Wednesday, May 1, 2013

C# string ToTitleCase. Capitalize the first letters of all words.

Convert string to title case. Capitalize the first letters of all words.


Sample code:
 
//include this
using System.Globalization;

//how to convert from uppercase string to titlecase
string title = "THE TITLE STRING";

TextInfo ti = CultureInfo.CurrentCulture.TextInfo;

title = ti.ToTitleCase(title.ToLower());

//result : "The Title String"
Additional Reading at :
  1. MSDN ToTitleCase

Wednesday, December 19, 2012

C# PadLeft and PadRight

PadLeft/PadRight is padding on the left/Right with spaces or a specified Unicode character for a specified total length. Example as bellow:
 
string myString = "";
int myInt = 1;
myString = myInt.ToString().PadLeft(8, '0'); 
//myString will be 00000001 
myString = myInt.ToString().PadRight(8, '0');
//myString will be 10000000
MSDN Pad Left
MSDN Pad Right

C# Convert Ascii string to Hex string vice versa

Convert Ascii to Hex method
 
public string ConvertAsciiToHex(string asciiString)
{
    string hex = "";
    foreach (char c in asciiString)
    {
       int tmp = c;
       hex += String.Format("{0:X2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
    }
    return hex;
}
Convert Hex to Ascii method
 
public string ConvertHextoAscii(string HexString)
{
    string asciiString = "";
    for (int i = 0; i < HexString.Length; i += 2)
    {
       if (HexString.Length >= i + 2)
       {
          String hs = HexString.Substring(i, 2);
          asciiString = asciiString + System.Convert.ToChar(System.Convert.ToUInt32(HexString.Substring(i, 2), 16)).ToString();
       }
    }
    return asciiString;
}

C# Reverse String Method

Reverse String Method as below
 
public static string ReverseString(string s)
{        
    char[] charArray = s.ToCharArray();
    Array.Reverse(charArray);
    return new string(charArray);
}

C# Convert Decimal to Binary and Vice Versa

Decimal to Binary conversion as below:
 
int DecimalVal = 256;
string BinaryVal = Convert.ToString(DecimalVal, 2);
Binary to Decimal conversion as below:
 
string BinaryVal = "01001101";
string DecimalVal = Convert.ToInt32(BinaryVal, 2).ToString();

C# Custom Value from DateTimePicker

Custom value from datetimepicker as below:
 
string date = DateTimePicker1.Value.ToString("yyyy-MM-dd");