Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C# String

C# String

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

Creating String Objects

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

The following example demonstrates this:

Example

using

System

;

namespace

StringApplication

{

   

class

Program

   

{

       

static

void

Main

(

string

[

]

args

)

       

{

           

// strings, string concatenation

           

string

fname, lname

;

            fname

=

"Rowan"

;

            lname

=

"Atkinson"

;

           

string

fullname

=

fname

lname

;

            Console

.

WriteLine

(

"Full Name: {0}"

, fullname

)

;

           

// by using a string constructor

           

char

[

]

letters

=

{

'H'

,

'e'

,

'l'

,

'l'

,

'o'

}

;

           

string

greetings

=

new

string

(

letters

)

;

            Console

.

WriteLine

(

"Greetings: {0}"

, greetings

)

;

           

// method returning 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 code above is compiled and executed, it produces the following result:


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

String Class Properties

The String class has the following two properties:

No. Property name & Description
1 Chars
Gets the character at the specified position in the current String String Char object.
2 Length
Gets the number of characters in the current String String object.

String Class Methods

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

No. Method name & Description
1 **public static int Compare( string strA, string strB ) **
Compares two specified string objects and returns an integer indicating their relative position in 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 indicating their relative position in sort order. However, if the Boolean parameter is true, the method is case-insensitive.
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 occurs within 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 ) **
Copy a specified number of characters from a specified position in a string object to a specified position in a Unicode character array.
9 **public bool EndsWith( string value ) **
Determine whether the end of a string object matches a specified string.
10 **public bool Equals( string value ) **
Determine whether the current string object has the same value as a specified string object.
11 **public static bool Equals( string a, string b ) **
Determine whether two specified string objects have the same value.
12 **public static string Format( string format, Object arg0 ) **
Replace one or more format items in a specified string with the string representation of a specified object.
13 **public int IndexOf( char value ) **
Return the index of the first occurrence of a specified Unicode character in the current string, with indexing starting at 0.
14 **public int IndexOf( string value ) **
Return the index of the first occurrence of a specified string in this instance, with indexing starting at 0.
15 **public int IndexOf( char value, int startIndex ) **
Return the index of the first occurrence of a specified Unicode character in this string, starting the search at a specified character position, with indexing starting at 0.
16 **public int IndexOf( string value, int startIndex ) **
Return the index of the first occurrence of a specified string in this instance, starting the search at a specified character position, with indexing starting at 0.
17 **public int IndexOfAny( char[] anyOf ) **
Return the index of the first occurrence in this instance of any character in a specified Unicode character array, with indexing starting at 0.
18 **public int IndexOfAny( char[] anyOf, int startIndex ) **
Return the index of the first occurrence in this instance of any character in a specified Unicode character array, starting the search at a specified character position, with indexing starting at 0.
19 **public string Insert( int startIndex, string value ) **
Return a new string in which a specified string is inserted at a specified index position in the current string object.
20 **public static bool IsNullOrEmpty( string value ) **
Indicate whether a specified string is null or an empty string.
21 **public static string Join( string separator, string[] value ) **
Concatenate all elements of a string array, separating each element with a specified delimiter.
22 **public static string Join( string separator, string[] value, int startIndex, int count ) **
Concatenate a specified number of elements from a specified position in a string array, separating each element with a specified delimiter.
23 **public int LastIndexOf( char value ) **
Return the index position of the last occurrence of a specified Unicode character in the current string object, with indexing starting at 0.
24 **public int LastIndexOf( string value ) **
Return the index position of the last occurrence of a specified string in the current string object, with indexing starting at 0.
25 **public string Remove( int startIndex ) **
Remove all characters from the current instance, starting at a specified position through the last position, and return the string.
26 **public string Remove( int startIndex, int count ) **
Remove a specified number of characters from a specified position in the current string and return the string.
27 **public string Replace( char oldChar, char newChar ) **
Replace all occurrences of a specified Unicode character in the current string object with another specified Unicode character and return a new string.
28 **public string Replace( string oldValue, string newValue ) **
Replace all occurrences of a specified string in the current string object with another specified string and return a new string.
29 **public string[] Split( params char[] separator ) **
Return a string array containing the substrings in the current string object, where the substrings are delimited by elements of a specified Unicode character array.
30 **public string[] Split( char[] separator, int count ) **
Return a string array containing the substrings in the current string object, where the substrings are delimited by elements of a specified Unicode character array; the int parameter specifies the maximum number of substrings to return.
31 **public bool StartsWith( string value ) **
Determine whether the beginning of a string instance matches a specified string.
32 public char[] ToCharArray()
Return a Unicode character array containing all characters in the current string object.
33 **public char[] ToCharArray( int startIndex, int length ) **
Return a Unicode character array containing all characters in the current string object, starting at a specified index and continuing for a specified length.
34 public string ToLower()
Convert the string to lowercase and return it.
35 public string ToUpper()
Convert the string to uppercase and return it.
36 public string Trim()
Remove all leading and trailing white-space characters from the current String object.

The above list of methods is not exhaustive; visit the MSDN library for the complete list of methods and the String class constructors.

Example

The following examples demonstrate some of the methods mentioned above:

Comparing strings

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 code above is compiled and executed, it produces the following result:


This is test and This is text are not equal.

String contains 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 code above is compiled and executed, it produces the following result:


The sequence 'test' was found.

Getting a 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 »

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


Last night I dreamt of San Pedro
San Pedro

Concatenate strings:

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 code above 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 sailing ship
And when I reached Jamaica
I made a stop