Detailed string and string_c# tutorials in C #

Source: Internet
Author: User
Tags constant lowercase string methods

Directory

    • lowercase string with uppercase string
    • Declaring and initializing a string
    • The immutability of a string
    • Regular string and literal string
    • Escape sequence for string
    • format string
    • Manipulating substrings
    • Null of String and "" (empty)
    • StringBuilder can be raised with high performance

Order

A string is an object of type string and its value is text. Internally, the text is stored as a sequential read-only collection of Char objects. There is no null-terminated character at the end of the C # string, so the C # string can contain any number of embedded null characters ("a"). The Length property of a string represents the number of Char objects it contains, not the number of Unicode characters. To access individual Unicode code bits in a string, use the StringInfo object.

lowercase string with uppercase string

In C #, the keyword string is an alias for string. Therefore, string is equivalent to string, which means you can use whichever you want. The string class provides a number of ways to safely create, manipulate, and compare strings. In addition, the C # language overloads certain operators to simplify common string operations.

Declaring and initializing a string

Take a look at the example:

static void Main (string[] args)
    {
      //declares but does not initialize 
      string msg1;
      Declared and initialized to null 
      string msg2 = null;
      Initializes as an empty string, using the Empty (empty) constant instead of the literal "" (empty)
      string msg3 = String.Empty;
      Initializes a string 
      OldPath = "C:\\Windows" with a regular string literal value;
      Initializes string 
      NewPath = @ "c:\windows" directly as a string;
      You can also use
      the System.String String content = "Hello world!";
      Use const to prevent MSG4 from being tampered with
      const string MSG4 = "I ' m const!";
      You can use an implicit type var
      var msg5 = "hi!";
      Initialize char[with String constructor
      ] letters = {' A ', ' B ', ' C '};
      String alphabet = new string (letters);
      Console.read ();
    }

"Attention" do not use the new operator to create a string object except when the string is initialized with a character array.

Initializes a string using the Empty constant value to create a new string object with zero length. The string representation of a 0 length string is "". Initializing a string by using the Empty value instead of NULL can reduce the likelihood of occurrence of NullReferenceException. We often use a static IsNullOrEmpty (string) method to validate the value of a string before attempting to access the string.

The immutability of a string

String objects are immutable: they cannot be changed after they are created. All the string methods that appear to modify strings and the operators in C # actually return the result as a new string object. In the following example, two original strings are not modified when the contents of S1 and S2 are concatenated to form a string. The + = operator creates a new string that contains the combined content. The new object is assigned to the variable s1, and the object originally assigned to S1 is released after it is garbage collected because no other variable contains a reference to it.

Example one:

static void Main (string[] args)
    {
      var s1 = "hi!";
      var s2 = "fanguzai!";
      Stitching S1 and S2, and modifying S1 pointing value
      s1 + = s2;  namely S1 = s1 + s2;
      Console.WriteLine (s1);
      Console.read ();
    }

Figure: var s1 = "hi!"; var s2 = "fanguzai!";

Figure: S1 = s1 + s2; Re-modify S1 pointing

Because the "modify" string is actually creating a new string, you must be cautious when creating a reference to a string. If you create a reference to a string and then "modify" the original string, the reference is still to the original object, not the new object that was created when the string was modified.

static void Main (string[] args)
    {
      var s1 = "hi!";
      var s2 = S1;
      After S1 the value, this time did not modify the S2 point value
      s1 + = "fanguzai!";  namely S1 = S1 + "fanguzai!";
      Console.WriteLine (S2);
      Console.read ();
    }

Figure: var s1 = "hi!"; s2 = S1; They point to the same reference address.

Figure: S1 = s1 + "fanguzai!"; Creates a "fanguzai!" without a reference and modifies the value that S1 points to.

Regular string and literal string

If you must embed the escape character provided by C #, you should use a regular string:

static void Main (string[] args)
    {
      var colustring = "Col1\tcol2\tcol3";
      var rowstring = "Row1\r\nrow2\r\nrow3";
       
      Console.WriteLine (colustring);
      Console.WriteLine ("=====");
      Console.WriteLine (rowstring);
      Console.read ();
    }

If the string literal contains a backslash character (for example, in a file path), use a literal string for convenience and readability. Because a literal string retains a newline character as part of the string literal, it can be used to initialize multiple-line strings. Use double quotes when you embed quotes in a literal string. The following example shows some common uses for literal strings:

static void Main (string[] args)
    {
      var path = @ "C:\Windows";
      var text = @ "Are you Fanguzai?
            " I ' m fanguzai! ';
       
      Console.WriteLine (path);
      Console.WriteLine ("=====");
      Console.WriteLine (text);
      Console.read ();
    }

Escape sequence for string

When "Memo" is compiled, the literal string is converted to a normal string that all escape sequences remain unchanged. Thus, if you view the literal string in the Debugger watch window, you will see the escape character added by the compiler, not the literal version in the source code. For example, the literal string @ "C:\temp.txt" appears as "C:\\temp.txt" in the Watch window.

format string

A format string is a string that the content can dynamically determine at run time. Create a format string in the following ways: Use the static Format method and embed placeholders in curly braces, which are replaced with other values at run time.

private static void Main (string[] args)
    {
      const string name = ' Fanguzai ';
      var s = string.  Format ("Hi, {0}!", name); Use Placeholder

      Console.WriteLine (s);
      Console.read ();
    }

Manipulating substrings

A substring is any sequence of characters contained within a string. You can use the Substring method to create a new string based on part of the original string. You can use the IndexOf method to search for one or more occurrences of a substring. Use the Replace method to replace all occurrences of a specified substring with a new string. As with the Substring method, Replace actually returns a new string without modifying the original string.

private static void Main (string[] args)
    {
      const string S1 = "Hi, fanguzai!";
      Console.WriteLine (S1.  Substring (4)); Intercept
      Console.WriteLine (S1.  Replace ("Hi", "Hello")); Replace
      Console.WriteLine (S1.  IndexOf (",", stringcomparison.ordinal)); Fetch index
      console.read ();
    }

Null of String and "" (empty)

An empty string is an instance of a System.String object that does not contain characters. Empty strings are often used in various programming scenarios to represent blank text fields. Methods can be called on empty strings because they are valid System.String objects.

var s = string.Empty;

Conversely, a null string does not refer to an instance of a System.String object, and any attempt to invoke a method on a null string will generate a NullReferenceException. However, you can use a null string with other strings in concatenation and comparison operations.

private static void Main (string[] args)
    {
      const string S1 = "Hi, fanguzai!";
      string s2 = null;
      var s3 = string. Empty;
      var s4 = s1 + s2; A value string with a null concatenation
      Console.WriteLine ("S4: {0}", S4);
      Console.WriteLine ("");
      var isTrue = (S2 = = s3);
      Console.WriteLine ("IsTrue: {0}", isTrue);
      Console.WriteLine ();
      var s5 = s3 + s2;
      Console.WriteLine ("S5: {0}", S5);
      Console.WriteLine ();
      Console.read ();
    }

StringBuilder can be raised with high performance

String operations in. NET are highly optimized and do not significantly affect performance in most cases. However, in some scenarios, such as in a loop that performs hundreds of or even hundreds of millions of times, string manipulation is likely to affect performance. The StringBuilder class creates a string buffer that provides better performance when a program performs a large number of string operations. The StringBuilder string can reassign individual characters (characters not supported by built-in string data types). For example, this code changes the contents of a string without creating a new string:

static void Main (string[] args)
    {
      var sb = new StringBuilder ("~ hi! Fanguzai! ");
      Sb[0] = ' ^ ';
      Console.WriteLine (SB);
      Console.read ();
    }

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.