C # Tutorial C # string (string)

Source: Internet
Author: User
C # String

In C #, you can use character arrays to represent strings, but it is more common to use the string keyword to declare a string variable. The string keyword is an alias for the System.String class.

Create a String object

You can use one of the following methods to thread a string object:

By assigning a string to the String variable

By using the String class constructor

By using the string concatenation operator (+)

By retrieving attributes or calling a method that returns a string

Formatting a value or object into its string representation

The following example demonstrates this:


using System;

namespace StringApplication
{
    class Program
    {
        static void Main (string [] args)
        {
           // string, string concatenation
            string fname, lname;
            fname = "Rowan";
            lname = "Atkinson";

            string fullname = fname + lname;
            Console.WriteLine ("Full Name: {0}", fullname);

            // by using the string constructor
            char [] letters = {'H', 'e', 'l', 'l', 'o'};
            string greetings = new string (letters);
            Console.WriteLine ("Greetings: {0}", greetings);

            // method returns a string
            string [] sarray = {"Hello", "From", "Tutorials", "Point"};
            string message = String.Join ("", sarray);
            Console.WriteLine ("Message: {0}", message);

            // Formatting method for converting values
            DateTime waiting = new DateTime (2012, 10, 10, 17, 58, 1);
            string chat = String.Format ("Message sent at {0: t} on {0: D}",
            waiting);
            Console.WriteLine ("Message: {0}", chat);
            Console.ReadKey ();
        }
    }
}




When the above code is compiled and executed, it produces the following results:


Full Name: Rowan Atkinson
Greetings: Hello
Message: Hello From Tutorials Point
Message: Message sent at 5:58 PM on Wednesday, October 10, 2012


String class properties

The String class has the following two properties:

Serial number

Property name & description

1 Chars
Gets the specified position of the Char object in the current String object.

2 Length
Gets the number of characters in the current String object.

Methods of class String

The String class has many methods for manipulating string objects. The following table provides some of the most commonly used methods:

Serial number

Method name & description

1 public static int Compare (string strA, string strB)
Compares two specified string objects and returns an integer that represents their relative position in the sort order. This method is case sensitive.

2 public static int Compare (string strA, string strB, bool ignoreCase)
Compares two specified string objects and returns an integer that represents their relative position in the sort order. However, this method is not case sensitive if the Boolean parameter is true.

3 public static string Concat (string str0, string str1)
Concatenates two string objects.

4 public static string Concat (string str0, string str1, string str2)
Concatenates three string objects.

5 public static string Concat (string str0, string str1, string str2, string str3)
Concatenates four string objects.

6 public bool Contains (string value)
Returns a value indicating whether the specified string object appears in the string.

7 public static string Copy (string str)
Creates a new String object with the same value as the specified string.

8 public void CopyTo (int sourceIndex, char [] destination, int destinationIndex, int count)
Copies the specified number of characters from the specified position in the string object to the specified position in the Unicode character array.

9 public bool EndsWith (string value)
Determines whether the end of the string object matches the specified string.

10 public bool Equals (string value)
Determines whether the current string object has the same value as the specified string object.

11 public static bool Equals (string a, string b)
Determines whether two specified string objects have the same value.

12 public static string Format (string format, Object arg0)
Replaces one or more format items in the specified string with the string representation of the specified object.

13 public int IndexOf (char value)
Returns the index of the first occurrence of the specified Unicode character in the current string, starting at 0.

14 public int IndexOf (string value)
Returns the index of the first occurrence of the specified string in this instance, starting at 0.

15 public int IndexOf (char value, int startIndex)
Returns the index of the first occurrence of the specified Unicode character starting at the specified character position in the string, starting at 0.

16 public int IndexOf (string value, int startIndex)
Returns the index of the first occurrence of the specified string from the specified character position in the instance, starting at 0.

17 public int IndexOfAny (char [] anyOf)
Returns the index of the first occurrence of any character in a specified Unicode character array in this instance, starting at 0.

18 public int IndexOfAny (char [] anyOf, int startIndex)
Returns the index of the first occurrence of any character in a specified Unicode character array, starting from the specified character position in the instance, starting at 0.

19 public string Insert (int startIndex, string value)
Returns a new string with the specified string inserted at the specified index position of the current string object.

20 public static bool IsNullOrEmpty (string value)
Indicates whether the specified string is null or an empty string.

21 public static string Join (string separator, params string [] value)
Concatenates all elements in a string array, separating each element with the specified delimiter.

22 public static string Join (string separator, string [] value, int startIndex, int count)
Links the specified elements in an array of strings, separating each element with the specified delimiter.

23 public int LastIndexOf (char value)
Returns the index position of the last occurrence of the specified Unicode character in the current string object, starting at 0.

24 public int LastIndexOf (string value)
Returns the index position of the last occurrence of the specified string in the current string object, starting at 0.

25 public string Remove (int startIndex)
Removes all characters from the current instance, starting at the specified position and continuing to the last position, and returns a string.

26 public string Remove (int startIndex, int count)
Removes the specified number of characters from the specified position in the current string and returns the string.

27 public string Replace (char oldChar, char newChar)
Replaces all specified Unicode characters in the current string object with another specified Unicode character and returns a new string.

28 public string Replace (string oldValue, string newValue)
Replaces all specified strings in the current string object with another specified string and returns a new string.

29 public string [] Split (params char [] separator)
Returns an array of strings containing the substrings in the current string object, the substrings being separated by the elements in the specified Unicode character array.

30 public string [] Split (char [] separator, int count)
Returns an array of strings containing the substrings in the current string object, the substrings being separated by the elements in the specified Unicode character array. The int parameter specifies the maximum number of substrings to return.

31 public bool StartsWith (string value)
Determines whether the beginning of a string instance matches the specified string.

32 public char [] ToCharArray ()
Returns an array of Unicode characters with all characters in the current string object.

33 public char [] ToCharArray (int startIndex, int length)
Returns a Unicode character array with all the characters in the current string object, starting at the specified index and ending at the specified length.

34 public string ToLower ()
Converts a string to lowercase and returns.

35 public string ToUpper ()
Converts a string to uppercase and returns.

36 public string Trim ()
Removes all leading and trailing whitespace characters from the current String object.

The list of methods above is not exhaustive, visit the MSDN library for a complete list of methods and the String class constructor.

Examples

The following examples demonstrate some of the methods mentioned above:

Compare strings


using System;

namespace StringApplication
{
   class StringProg
   {
      static void Main(string[] args)
      {
         string str1 = "This is test";
         string str2 = "This is text";

         if (String.Compare(str1, str2) == 0)
         {
            Console.WriteLine(str1 + " and " + str2 +  " are equal.");
         }
         else
         {
            Console.WriteLine(str1 + " and " + str2 + " are not equal.");
         }
         Console.ReadKey() ;
      }
   }
}










When the above code is compiled and executed, it produces the following results:

This is test and This is text are not equal.
The string contains strings:


using System;

namespace StringApplication
{
   class StringProg
   {
      static void Main(string[] args)
      {
         string str = "This is test";
         if (str.Contains("test"))
         {
            Console.WriteLine("The sequence 'test' was found.");
         }
         Console.ReadKey() ;
      }
   }
}








When the above code is compiled and executed, it produces the following results:

The sequence 'test' was found.
Get the substring:

using System;

namespace StringApplication
{
   class StringProg
   {
      static void Main(string[] args)
      {
         string str = "Last night I dreamt of San Pedro";
         Console.WriteLine(str);
         string substr = str.Substring(23);
         Console.WriteLine(substr);
      }
      Console.ReadKey() ;
   }
}








When the above code is compiled and executed, it produces the following results:

San Pedro


Connection string:


using System;

namespace StringApplication
{
   class StringProg
   {
      static void Main(string[] args)
      {
         string[] starray = new string[]{"Down the way nights are dark",
         "And the sun shines daily on the mountain top",
         "I took a trip on a sailing ship",
         "And when I reached Jamaica",
         "I made a stop"};

         string str = String.Join("\n", starray);
         Console.WriteLine(str);
      }
      Console.ReadKey() ;
   }
}





When the above code is compiled and executed, it produces the following results:

Down the way nights are dark
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop


  The above is the content of [c # tutorial] C # String. For more related content, please pay attention to topic.alibabacloud.com (www.php.cn)!

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.