C# String Methods IsEmpty, Find, Replace

IsEmpty, Find, Replace - Comparison C# vs MFC (CString)

IsEmpty, Find, and Replace are common used string methods in MFC (CString class).

MFC (CString) Samples:
CString somestring = L"ABCDEFG";

if (somestring.IsEmpty())
{
    // somestring is empty
}

if (somestring.Find(L"ABC")!=-1)
{
    // found "ABC" in somestring
}

somestring.Replace(L"ABC",L"abc");
// somestring == L"abcDEFG"

 

In C# we use string.IsNullOrEmpty instead of IsEmpty and IndexOf instead of Find:

MFC (CString) C# (string)
somestring.IsEmpty() string.IsNullOrEmpty(somestring)
somestring.Find (str) somestring.IndexOf(str)
somestring.Replace (strold,strnew) somestring = somestring.Replace(strold,strnew)

 

See also: Comparison of string operations: Left, Mid, Right - C# vs MFC

 

 

Check for an Empty String: IsNullOrEmpty in C#

Checks if a string is Null or Empty:

// Sample: Check if somestring is empty
string somestring = string.Empty;
if (string.IsNullOrEmpty(somestring))
{
    // somestring is empty
}

Don't use comparisons like:
if (somestring.Length==0) ... or
if (somestring=="") ...
The comparison will result in an exception(!) if somestring == string.Empty or somestring == Null (no object available)

 

Search in a String: IndexOf in C#

Search for a string inside a string and return the index ( index==-1 if string not found)

// Sample: Search for "DEF" inside "ABCDEFG"
string somestring = "ABCDEFG";
int index = somestring.IndexOf("DEF");
// index == 3 (starts by 0)

if (index == -1)
{
    // not found
}

 

Replace String in C#

Replace a string inside a string:

// Sample: Replace "ABC" with "abc" inside "ABCDEFG"
string somestring = "ABCDEFG";
somestring = somestring.Replace("ABC","abc");
// somestring == "abcDEFG"

"Replace" returns a new string ... it does not change the "old" string, so you need to use: "somestring = somestring.Replace(...)"

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