C#note 03: string

来源:互联网 发布:小土豆编程 编辑:程序博客网 时间:2024/05/22 05:15

String 

A C# string is a group of one or more characters declared using the string keywork, which is a C# language shortcut for the System.String class. 

String objects are immutable in that they cannot be changed once created. Methods that act on strings actually return new string objects. Therefore, for performance reasons, large amounts of concatenation or other involved string manipulation should be performed with the StringBuilder class.

The @ Symbol

The @ Symbol specifies that escape characters and line breaks should be ignored when the string is created. The following two strings are therefore identical:

string p1 = "////My Documents//My Files//";

string p2 = @"//My Documents/My Files/";

 

ToString()

The C# built-in data types all provide the ToString method, which converts a value to a string. This method can be used to convert numeric values into strings.

Individual characters constianed in a string can be accessed using methods such as Substring, Replace, Split and Trim.

It is also possible to copy the characters into a character array.

Individual characters from a string can be accessed with an index.

To change the letters in a string to upper or lower case, use ToUpper() or ToLower().

The best way to compare two non-localized strings is to use the Equals method with the StringComparison.Ordinal and StringComparison.OrdinalIgnoreCase.

String objects also have a CompareTo() method that returns an integer value based on whether one string is less-than or greater-than another. When comparing strings, the Unicode value is used, and lower case has a smaller value that upper case.

To search for a string inside another string, use IndexOf(). IndexOF() returns -1 if the search string is not found; otherwise, it returns the zero-based index of the first location at which it occurs.

Splitting a string into substrins, such as, splitting a sentence into individual words, is a common programming task. The Split() method takes a char array of delimiters, for exaple, a space character, and returns an array of substirngs.

 

Using StringBuilder 

The StringBuilder class creates a string buffer that offers better performance if your program persorms a lot of string manipulation. The StringBuilder class also allows you to reassign individual characters, something the built-in string data type does not support. 

原创粉丝点击