You can instantiate a String object in the following ways:
- By assigning a string literal to a String variable. This is the most commonly used method for creating a string. The following example uses assignment to create several strings. Note that in C#, because the backslash (\) is an escape character, literal backslashes in a string must be escaped or the entire string must be @-quoted.C#
string string1 = "This is a string created by assignment."; Console.WriteLine(string1); string string2a = "The path is C:\\PublicDocuments\\Report1.doc"; Console.WriteLine(string2a); string string2b = @"The path is C:\PublicDocuments\Report1.doc"; Console.WriteLine(string2b); // The example displays the following output: // This is a string created by assignment. // The path is C:\PublicDocuments\Report1.doc // The path is C:\PublicDocuments\Report1.doc
By calling a String class constructor. The following example instantiates strings by calling several class constructors. Note that some of the constructors include pointers to character arrays or signed byte arrays as parameters. Visual Basic does not support calls to these constructors. For detailed information about String constructors, see the String constructor summary.
C#
char[] chars = { 'w', 'o', 'r', 'd' };
sbyte[] bytes = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x00 };
// Create a string from a character array.
string string1 = new string(chars);
Console.WriteLine(string1);
// Create a string that consists of a character repeated 20 times.
string string2 = new string('c', 20);
Console.WriteLine(string2);
string stringFromBytes = null;
string stringFromChars = null;
unsafe
{
fixed (sbyte* pbytes = bytes)
{
// Create a string from a pointer to a signed byte array.
stringFromBytes = new string(pbytes);
}
fixed (char* pchars = chars)
{
// Create a string from a pointer to a character array.
stringFromChars = new string(pchars);
}
}
Console.WriteLine(stringFromBytes);
Console.WriteLine(stringFromChars);
// The example displays the following output:
// word
// cccccccccccccccccccc
// ABCDE
// word
1 comment:
Thanks for any other excellent article. The place
else may anybody get that kind of info in such an ideal means of writing?
I have a presentation next week, and I'm at the search
for such information.
Post a Comment