C#note 03: string

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. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值