C # string


Release date:2023-08-30 Update date:2023-10-13 Editor:admin View counts:350

Label:

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. string keyword is System.String alias for the class.

Create a String object

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

  • By giving String variable specifies a string

  • By using the String class constructor

  • By using the string concatenation operator ( + )

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

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

The following example demonstrates this:

Example

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: RowanAtkinson
Greetings: Hello
Message: Hello From Tutorials Point
Message: Message sent at 17:58 on Wednesday, 10 October 2012

Properties of the String class

String class has the following two properties:

Serial number

Attribute name & description

1

Chars gets the specified location of the Char object in the current String object.

2

Length gets the number of characters in the current String object.

Methods of the String class

String class has a number of methods for string object. The following table provides some of the most common 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 representstheir relative position in the sort order. However, if the Boolean parameter is true, the method is case-insensitive.

3

Public static string Concat (string str0, string str1) connects two string objects.

4

Public static string Concat (string str0, string str1, string str2) connectsthree string objects.

5

Public static string Concat (string str0, string str1, string str2, string str3) connects 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 of the string object to the specified position in theUnicode character array.

9

Public bool EndsWith (string value) determines whether the end of the stringobject 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 at which the specified Unicode character appears for the first time in the current string, startingat 0.

14

Public int IndexOf (string value) returns the index of the first occurrence of the specified string in the instance, starting at 0.

15

Public int IndexOf (char value, int startIndex) returns the specified Unicode character to search for the first occurrence of the index from the specified character position in the string, starting at 0.

16

Public int IndexOf (string value, int startIndex) returns the specified string to search for the first occurrence of the index from the specified character position in the instance, starting at 0.

17

Public int IndexOfAny (char [] anyOf) returns the index of any character in a specified array of Unicode characters that first appears in the instance, starting at 0.

18

Public int IndexOfAny (char [] anyOf, int startIndex) returns any character in a specified Unicode character array to search for the first occurrence ofthe index from the specified character position in the instance, starting at 0.

19

Public string Insert (int startIndex, string value) returns a new string where the specified string is inserted at the specified index of the currentstring 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, string [] value) concatenates all the 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) concatenates the specified elements starting at the specified position in a string array, separating each element with the specified delimiter.

23

Public int LastIndexOf (char value) returns the index position where the specified Unicode character last appeared in the current string object, starting at 0.

24

Public int LastIndexOf (string value) returns the index position of the lastoccurrence 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, from the specified position to the last position, and returns the string.

26

Public string Remove (int startIndex, int count) removes the specified number of characters from the specified position of 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 stringand returns the new string.

29

Public string [] Split( params char[] Separator) returns an array of stringscontaining the substrings in the current string object, which are separatedby elements from 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, which are separated by elements from 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 the characters in the current string object.

33

Public char [] ToCharArray (int startIndex, int length) returns an array of Unicode characters 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 the string to lowercase and returns.

35

Public string ToUpper () converts the string to uppercase and returns.

36

Public string Trim () removes all leading and trailing white space characters from the current String object.

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

Example

The following examples demonstrate some of the methods mentioned above:

Compare string

Example

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.

A string contains a string:

Example

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:

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

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

Last night I dreamt of San Pedro
San Pedro

Connection string:

Example

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

Powered by TorCMS (https://github.com/bukun/TorCMS).