C# String Methods IsEmpty, Find, Replace
IsEmpty, Find, Replace - Comparison C# vs MFC (CString)
Web Form Builder
Software for Beginner and Professionals
Learn more Trial version available!
check Design forms using a visual environment
check Form and design templates included
check Generated PHP script runs on your own website
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(...)"