C# Tutoriallogin
C# Tutorial
author:php.cn  update time:2022-04-11 14:06:23

C# String



In C#, you can use a character array to represent a string, however, 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.

Creating a String object

You can create a string object using one of the following methods:

  • By specifying a string to the String variable

  • By using the String class constructor

  • By using the string concatenation operator ( + )

  • By retrieving properties or calling a method that returns a string

  • Convert a value or object to its string representation by formatting methods

The following example demonstrates this:

using System;

namespace StringApplication
{
    class Program
    {
        static void Main(string[] args)
        {
           //字符串,字符串连接
            string fname, lname;
            fname = "Rowan";
            lname = "Atkinson";

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

            //通过使用 string 构造函数
            char[] letters = { 'H', 'e', 'l', 'l','o' };
            string greetings = new string(letters);
            Console.WriteLine("Greetings: {0}", greetings);

            //方法返回字符串
            string[] sarray = { "Hello", "From", "Tutorials", "Point" };
            string message = String.Join(" ", sarray);
            Console.WriteLine("Message: {0}", message);

            //用于转化值的格式化方法
            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: RowanAtkinson
Greetings: Hello
Message: Hello From Tutorials Point
Message: Message sent at 17:58 on Wednesday, 10 October 2012

String class properties

String class has the following two attributes:

##12

Methods of the String class

The String class has many methods for operating on string objects. The table below provides some of the most commonly used methods:

Serial numberAttribute name & description
CharsGet the specified position of the
Char object in the current String object.
LengthGet the number of characters in the current
String object.
Serial numberMethod name & description
1public static int Compare( string strA, string strB )
Compares two specified string objects and returns an integer representing their relative position in the sorting order. This method is case-sensitive.
2public static int Compare( string strA, string strB, bool ignoreCase )
Compares two specified string objects and returns an integer representing their relative position in the sorting order. However, if the boolean argument is true, the method is not case sensitive.
3public static string Concat( string str0, string str1 )
Connect two string objects.
4public static string Concat( string str0, string str1, string str2 )
Connect three string objects.
5public static string Concat( string str0, string str1, string str2, string str3 )
Connect four string objects.
6public bool Contains( string value )
Returns a value indicating whether the specified string object appears in the string.
7public static string Copy( string str )
Creates a new String object with the same value as the specified string.
8public void CopyTo( int sourceIndex, char[] destination, int destinationIndex, int count )
Copy the specified number of characters starting from the specified position of the string object to the specified position in the Unicode character array.
9public bool EndsWith( string value )
Determine whether the end of the string object matches the specified string.
10public bool Equals( string value )
Determine whether the current string object has the same value as the specified string object.
11public static bool Equals( string a, string b )
Determine whether two specified string objects have the same value.
12public static string Format( string format, Object arg0 )
Replace one or more format items in the specified string with the string representation of the specified object.
13public int IndexOf( char value )
Returns the index of the first occurrence of the specified Unicode character in the current string, starting from 0.
14public int IndexOf( string value )
Returns the index of the first occurrence of the specified string in this instance, starting from 0.
15public int IndexOf( char value, int startIndex )
Returns the index of the first occurrence of the specified Unicode character in this string, starting at the specified character position, starting at 0.
16public int IndexOf( string value, int startIndex )
Returns the index of the first occurrence of the specified string starting from the specified character position in this instance. The index starts from 0.
17public int IndexOfAny( char[] anyOf )
Returns the index of the first occurrence of any character in a specified Unicode character array in this instance. The index starts from 0.
18public 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, and the index starts from 0.
19public string Insert( int startIndex, string value )
Returns a new string in which the specified string is inserted at the specified index of the current string object.
20public static bool IsNullOrEmpty( string value )
Indicates whether the specified string is null or an empty string.
21public static string Join( string separator, params string[] value )
Concatenates all elements in a string array, using the specified delimiter to separate each element.
22public static string Join( string separator, string[] value, int startIndex, int count )
Connect the specified elements starting at the specified position in a string array, using the specified delimiter to separate each element.
23public int LastIndexOf( char value )
Returns the index position of the last occurrence of the specified Unicode character in the current string object. The index starts from 0.
24public int LastIndexOf( string value )
Returns the index position of the last occurrence of the specified string in the current string object. The index starts from 0.
25public string Remove( int startIndex )
Removes all characters in the current instance, starting from the specified position to the last position, and returns the string.
26public string Remove( int startIndex, int count )
Remove the specified number of characters starting from the specified position of the current string and return the string.
27public string Replace( char oldChar, char newChar )
Replace all specified Unicode characters in the current string object with another specified Unicode character and return the new string.
28public string Replace( string oldValue, string newValue )
Replaces all specified strings in the current string object with another specified string and returns the new string.
29public string[] Split( params char[] separator )
Returns a string array containing the substrings in the current string object, separated by elements in the specified Unicode character array.
30public string[] Split( char[] separator, int count )
Returns a string array containing the substrings in the current string object, separated by elements in the specified Unicode character array. The int parameter specifies the maximum number of substrings to return.
31public bool StartsWith( string value )
Determine whether the beginning of the string instance matches the specified string.
32public char[] ToCharArray()
Returns a Unicode character array with all the characters in the current string object.
33public 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.
34public string ToLower()
Convert the string to lowercase and return it.
35public string ToUpper()
Convert the string to uppercase and return.
36public string Trim()
Removes all leading and trailing whitespace characters from the current String object.

The above method list is not exhaustive, please visit the MSDN library to see the complete method list and 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 When the code is compiled and executed, it produces the following result:

This is test and This is text are not equal.

The string contains the string:

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 Will produce the following results:

The sequence 'test' was found.

Get the substring:

##Example

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() ; 
		} 
	} 
}

Run Example»Click the "Run Example" button to view the online example


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

Last night I dreamt of San Pedro
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 will produce 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