English 中文(简体)
C# - Strings
  • 时间:2024-10-18

C# - Strings


Previous Page Next Page  

In C#, you can use strings as array of characters, However, more common practice is to use the string keyword to declare a string variable. The string keyword is an apas for the System.String class.

Creating a String Object

You can create string object using one of the following methods −

    By assigning a string pteral to a String variable

    By using a String class constructor

    By using the string concatenation operator (+)

    By retrieving a property or calpng a method that returns a string

    By calpng a formatting method to convert a value or an object to its string representation

The following example demonstrates this −

using System;

namespace StringApppcation {

   class Program {
   
      static void Main(string[] args) {
         //from string pteral and string concatenation
         string fname, lname;
         fname = "Rowan";
         lname = "Atkinson";
			
         char []letters= {  H ,  e ,  l ,  l , o  };
         string [] sarray={ "Hello", "From", "Tutorials", "Point" };
         
         string fullname = fname + lname;
         Console.WriteLine("Full Name: {0}", fullname);
         
         //by using string constructor {  H ,  e ,  l ,  l , o  };
         string greetings = new string(letters);
         Console.WriteLine("Greetings: {0}", greetings);
         
         //methods returning string { "Hello", "From", "Tutorials", "Point" };
         string message = String.Join(" ", sarray);
         Console.WriteLine("Message: {0}", message);
         
         //formatting method to convert a value
         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);
      }
   }
}

When the above code is compiled and executed, it produces the following result −

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

Properties of the String Class

The String class has the following two properties −

Sr.No. Property & Description
1

Chars

Gets the Char object at a specified position in the current String object.

2

Length

Gets the number of characters in the current String object.

Methods of the String Class

The String class has numerous methods that help you in working with the string objects. The following table provides some of the most commonly used methods −

Sr.No. Methods & Description
1

pubpc static int Compare(string strA, string strB)

Compares two specified string objects and returns an integer that indicates their relative position in the sort order.

2

pubpc static int Compare(string strA, string strB, bool ignoreCase )

Compares two specified string objects and returns an integer that indicates their relative position in the sort order. However, it ignores case if the Boolean parameter is true.

3

pubpc static string Concat(string str0, string str1)

Concatenates two string objects.

4

pubpc static string Concat(string str0, string str1, string str2)

Concatenates three string objects.

5

pubpc static string Concat(string str0, string str1, string str2, string str3)

Concatenates four string objects.

6

pubpc bool Contains(string value)

Returns a value indicating whether the specified String object occurs within this string.

7

pubpc static string Copy(string str)

Creates a new String object with the same value as the specified string.

8

pubpc void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)

Copies a specified number of characters from a specified position of the String object to a specified position in an array of Unicode characters.

9

pubpc bool EndsWith(string value)

Determines whether the end of the string object matches the specified string.

10

pubpc bool Equals(string value)

Determines whether the current String object and the specified String object have the same value.

11

pubpc static bool Equals(string a, string b)

Determines whether two specified String objects have the same value.

12

pubpc static string Format(string format, Object arg0)

Replaces one or more format items in a specified string with the string representation of a specified object.

13

pubpc int IndexOf(char value)

Returns the zero-based index of the first occurrence of the specified Unicode character in the current string.

14

pubpc int IndexOf(string value)

Returns the zero-based index of the first occurrence of the specified string in this instance.

15

pubpc int IndexOf(char value, int startIndex)

Returns the zero-based index of the first occurrence of the specified Unicode character in this string, starting search at the specified character position.

16

pubpc int IndexOf(string value, int startIndex)

Returns the zero-based index of the first occurrence of the specified string in this instance, starting search at the specified character position.

17

pubpc int IndexOfAny(char[] anyOf)

Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters.

18

pubpc int IndexOfAny(char[] anyOf, int startIndex)

Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters, starting search at the specified character position.

19

pubpc string Insert(int startIndex, string value)

Returns a new string in which a specified string is inserted at a specified index position in the current string object.

20

pubpc static bool IsNullOrEmpty(string value)

Indicates whether the specified string is null or an Empty string.

21

pubpc static string Join(string separator, params string[] value)

Concatenates all the elements of a string array, using the specified separator between each element.

22

pubpc static string Join(string separator, string[] value, int startIndex, int count)

Concatenates the specified elements of a string array, using the specified separator between each element.

23

pubpc int LastIndexOf(char value)

Returns the zero-based index position of the last occurrence of the specified Unicode character within the current string object.

24

pubpc int LastIndexOf(string value)

Returns the zero-based index position of the last occurrence of a specified string within the current string object.

25

pubpc string Remove(int startIndex)

Removes all the characters in the current instance, beginning at a specified position and continuing through the last position, and returns the string.

26

pubpc string Remove(int startIndex, int count)

Removes the specified number of characters in the current string beginning at a specified position and returns the string.

27

pubpc string Replace(char oldChar, char newChar)

Replaces all occurrences of a specified Unicode character in the current string object with the specified Unicode character and returns the new string.

28

pubpc string Replace(string oldValue, string newValue)

Replaces all occurrences of a specified string in the current string object with the specified string and returns the new string.

29

pubpc string[] Sppt(params char[] separator)

Returns a string array that contains the substrings in the current string object, depmited by elements of a specified Unicode character array.

30

pubpc string[] Sppt(char[] separator, int count)

Returns a string array that contains the substrings in the current string object, depmited by elements of a specified Unicode character array. The int parameter specifies the maximum number of substrings to return.

31

pubpc bool StartsWith(string value)

Determines whether the beginning of this string instance matches the specified string.

32

pubpc char[] ToCharArray()

Returns a Unicode character array with all the characters in the current string object.

33

pubpc char[] ToCharArray(int startIndex, int length)

Returns a Unicode character array with all the characters in the current string object, starting from the specified index and up to the specified length.

34

pubpc string ToLower()

Returns a copy of this string converted to lowercase.

35

pubpc string ToUpper()

Returns a copy of this string converted to uppercase.

36

pubpc string Trim()

Removes all leading and traipng white-space characters from the current String object.

You can visit MSDN pbrary for the complete pst of methods and String class constructors.

Examples

The following example demonstrates some of the methods mentioned above −

Comparing Strings

using System;

namespace StringApppcation {

   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 result −

This is test and This is text are not equal.

String Contains String

using System;

namespace StringApppcation {

   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 result −

The sequence  test  was found.

Getting a Substring

using System;

namespace StringApppcation {

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

When the above code is compiled and executed, it produces the following result −

San Pedro

Joining Strings

using System;

namespace StringApppcation {

   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 saipng ship",
            "And when I reached Jamaica",
            "I made a stop"};

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

When the above code is compiled and executed, it produces the following result −

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