C# String Operations (Methods) Left, Mid, Right

Left, Mid, Right - Comparison C# vs MFC (CString)

Left, Mid and Right are common used string operations in MFC (CString class).

MFC (CString) Samples:
CString somestring = L"ABCDEFG";
somestring.Left(3) == L"ABC"
somestring.Mid(2,3) == L"CDE"
somestring.Mid (2) == L"CDEFG"
somestring.Right(3) == L"EFG"
The index starts at 0 (MFC and C#), so nIndex=2 means the 3rd char!

 

In C# we use Substring instead of Left, Mid and Right:

MFC (CString) C# (string)
somestring.Left(nCount) somestring.Substring(0,nCount)
somestring.Mid(nIndex) somestring.Substring(nIndex)
somestring.Mid(nIndex,nCount) Somestring.Substring(nIndex,nCount)
somestring.Right(nCount) somestring.Substring(somestring.Length-nCount,nCount)

 

See also: Comparison of string methods: IsEmpty, Find, Replace - C# vs MFC

 

 

String Left (number of chars) in C#

Extract the first nCount characters (leftmost) from a string:

// Sample: Extract the first 3 chars "ABC" from "ABCDEFG"
// Important: Don't forget to make sure the string is not empty or too short!

string somestring = "ABCDEFG";
string newstring = somestring.Substring(0, 3);

 

String Right (number of chars) in C#

Extract the last nCount characters (rightmost) from a string:

// Sample: Extract the last 3 chars "EFG" from "ABCDEFG"
// Important: Don't forget to make sure the string is not empty or too short!

string somestring = "ABCDEFG";
string newstring = somestring.Substring(somestring.Length-3, 3);

 

String Mid (index, number of chars) in C#

Extract nCount characters starting at nIndex from a string:

// Sample: Extract 3 chars (starting at 'C') from "ABCDEFG" (nIndex=2 nCount=3)
// Important: Don't forget to make sure the string is not empty or too short!

string somestring = "ABCDEFG";
string newstring = somestring.Substring(2, 3);

 

String Mid (index) in C#

Extract ALL characters starting at nIndex from a string:

// Sample: Extract ALL chars (starting at 'C') from "ABCDEFG" (nIndex=2)
// Important: Don't forget to make sure the string is not empty or too short!

string somestring = "ABCDEFG";
string newstring = somestring.Substring(2);

Disclaimer: The information on this page is provided "as is" without warranty of any kind. Further, Arclab Software OHG does not warrant, guarantee, or make any representations regarding the use, or the results of use, in terms of correctness, accuracy, reliability, currentness, or otherwise. See: License Agreement