字符串

字符串

string数据类型,它是String类的别名。

 

使用字符串

C#字符串是使用string关键字声明的一个字符数组。字符串是使用引号声明的,如下例所示:

string s = "Hello, World!";

您可以提取字符串和连接字符串,如下所示:

string s1 = "orange";

string s2 = "red";

 

s1 += s2;

System.Console.WriteLine(s1);  // outputs "orangered"

 

s1 = s1.Substring(2, 5);

System.Console.WriteLine(s1);  // outputs "anger"

字符串对象是“不可变的”,即它们一旦创建就无法更改。对字符串进行操作的方法实际上返回的是新的字符串对象。在前面的示例中,将s1s2的内容连接起来以构成一个字符串时,包含“orange”和“red”的两个字符串均保持不变。+=运算符会创建一个包含组合内容的新字符串。结果是s1现在引用一个完全不同的字符串。只包含“orange”的字符串仍然存在,但连接s1后将不再被引用。

因此,处于性能方面的原因,大量的连接或其他涉及字符串的操作应当用StringBuilder类执行,如下所示:

System.Text.StringBuilder sb = new System.Text.StringBuilder();

sb.Append("one ");

sb.Append("two ");

sb.Append("three");

string str = sb.ToString();

 

转义符

字符串中可以包含转义符,如“/n(新行)和“/t(制表符),如:

string hello = "Hello/nWorld!";

等同于

Hello

World!

如果希望包含反斜杠,则它前面必须还有另一个反斜杠。下面的字符串:

string filePath = "////My Documents//";

实际上等同于:

//My Documents/

@符号

@符号会告知字符串构造函数忽略转义符和分行符。因此,以下两个字符串是完全相同的:

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

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

ToString()

如同所有从Object派生的对象一样,字符串也提供了ToString方法,用于将值装换为字符串。此方法可用于将数值转换为字符串,如下所示:

int year = 1999;

string msg = "Eve was born in " + year.ToString();

System.Console.WriteLine(msg);  // outputs "Eve was born in 1999"

访问各个字符

字符串中所包含的各个字符可以使用以下方法进行访问,如SubString()Replace()Split()Trim()

string s3 = "Visual C# Express";

 

System.Console.WriteLine(s3.Substring(7, 2));         // outputs "C#"

System.Console.WriteLine(s3.Replace("C#", "Basic"));  // outputs "Visual Basic Express"

也可以将字符复制到字符数组,如下所示:

string s4 = "Hello, World";

char[] arr = s4.ToCharArray(0, s4.Length);

 

foreach (char c in arr)

{

    System.Console.Write(c);  // outputs "Hello, World"

}

可以用索引访问字符串中的各个字符,如下所示:

string s5 = "Printing backwards";

 

for (int i = 0; i < s5.Length; i++)

{

    System.Console.Write(s5[s5.Length - i - 1]);  // outputs "sdrawkcab gnitnirP"

}

更改大小写

若要将字符串中的字母更改为大写或小写,可以使用ToUpper()ToLower(),如下所示:

string s6 = "Battle of Hastings, 1066";

 

System.Console.WriteLine(s6.ToUpper());  // outputs "BATTLE OF HASTINGS 1066"

System.Console.WriteLine(s6.ToLower());  // outputs "battle of hastings 1066"

比较

比较两个字符串的最简单方法是使用==!=运算符,执行区分大小写的比较。

string color1 = "red";

string color2 = "green";

string color3 = "red";

 

if (color1 == color3)

{

    System.Console.WriteLine("Equal");

}

if (color1 != color2)

{

    System.Console.WriteLine("Not equal");

}

字符串对象也有一个CompareTo()方法,它根据某个字符串是否小于(<)或大于(>)另一个,返回一个整数值。比较字符串时使用Unicode值,小写的值小于大写的值。

string s7 = "ABC";

string s8 = "abc";

 

if (s7.CompareTo(s8) > 0)

{

    System.Console.WriteLine("Greater-than");

}

else

{

    System.Console.WriteLine("Less-than");

}

若要在一个字符串中搜索另一个字符串,可以使用IndexOf()。如果未找到搜索字符串,IndexOf()返回-1;否则,返回它出现的第一个位置的索引(从零开始)

string s9 = "Battle of Hastings, 1066";

 

System.Console.WriteLine(s9.IndexOf(" Hastings "));  // outputs 10

System.Console.WriteLine(s9.IndexOf("1967"));      // outputs -1

将字符串拆分为子字符串

将字符串拆分为子字符串(如将句子拆分为各个单词)是一个常见的编程任务。Split()方法使用分隔符(如空格字符)char数组,并返回一个字符串数组。您可以使用foreach访问此数组,如下所示:

char[] delimit = new char[] { ' ' };

string s10 = "The cat sat on the mat.";

foreach (string substr in s10.Split(delimit))

{

    System.Console.WriteLine(substr);

}

此代码将在单独的行上输出每个单词,如下所示:

The

cat

sat

on

the

mat.

使用StringBuilder

StringBuilder类创建了一个字符串缓冲区,用于在程序执行大量字符串操作时提供更好的性能。StringBuilder字符串还允许您重新分配个别字符,这些字符是内置字符串数据类型所不支持的。例如,此代码在不创建新字符串的情况下更改了一个字符串的内容:

System.Text.StringBuilder sb = new System.Text.StringBuilder("Rat: the ideal pet");

sb[0] = 'C';

System.Console.WriteLine(sb.ToString());

System.Console.ReadLine();

在本示例中,StringBuilder对象用于从一组数值类型中创建字符串:

class  TestStringBuilder {
        
static void Main(){
                System.Text.StringBuilder sb 
= new System.Text.StringBuilder();
                
                
//Create a string composed of numbers 0 - 9
                for (int i = 0; i < 10; i++){
                        sb.Append(i.ToString());
                    }

                System.Console.WriteLine(sb);        
//displays 0123456789
                
                
//Copy one character of the string (not possible with a System.String)
                sb[0= sb[9];
                
                System.Console.WriteLine(sb);        
//displays 9123456789
            }

    }

 

如何:使用Split方法分析字符串

下面的代码示例演示如何使用System.String.Split方法分析字符串。此方法返回一个字符串数组,其中每个元素是一个单词。作为输入,Split采用一个字符数组指示哪些字符被用作分隔符。本示例中使用了空格、逗号、句号、冒号和制表符。一个含有这些分隔符的数组被传递给Split,并使用结果字符串数组分别显示句子中的每个单词。

示例

class  TestStringSplit {
        
static void Main(){
                
char[] delimiterChars = {' ',',','.',':',' '};
                
                
string text = "one two three:four,five six seven";
                System.Console.WriteLine(
"Original text: '{0}'",text);
                
                
string[] words = text.Split(delimiterChars);
                System.Console.WriteLine(
"{0} words in text:",words.Length);
                
                
foreach (string s in words){
                        System.Console.WriteLine(s);
                    }

            }

    }


如何:使用字符串方法搜索字符串

string类型(它是System.String类的别名)为搜索字符串的内容提供了许多有用的方法。下面的示例使用IndexOfLastIndexOfStartsWithEndsWith方法。

示例

class  StringSearch {
        
static void Main(){
                
string str = "A silly sentence used for silly purposes.";
                System.Console.WriteLine(
"'{0}'",str);
                
                
bool test1 = str.StartsWith("a silly");
                System.Console.WriteLine(
"starts with 'a silly'? {0}",test1);
                
                
bool test2 = str.StartsWith("a silly",System.StringComparison.OrdinalIgnoreCase);
                System.Console.WriteLine(
"starts with 'a silly'? {0} (ignoring case)",test2);
                
                
bool test3 = str.EndsWith(".");
                System.Console.WriteLine(
"ends with '.'? {0}",test3);
                
                
int first = str.IndexOf("silly");
                
int last = str.LastIndexOf("silly");
                
string str2 = str.Substring(first,last - first);
                System.Console.WriteLine(
"between two 'silly' words: '{0}'",str2);
            }

    }


如何:使用正则表达式搜索字符串

可以使用System.Text.ReqularExpressions.Regex类搜索字符串。这些搜索可以涵盖从非常简单到全面使用正则表达式的复杂范围。以下是使用Regex类搜索字符串的两个示例。

示例

以下代码是一个控制台应用程序,用于对数组中的字符串执行简单的不区分大小写的搜索。给定要搜索的字符串和包含搜索模式的字符串后,静态方法System.Text.RegularExpressions.Regex.IsMatch(System.String,System.String,System.Text.RegularExpressions.RegexOptions)

class  TestRegularExpressions {
        
static void Main(){
                
string[] sentences = {
                        
"cow over the moon",
                        
"Betsy the Cow",
                        
"cowering in the corner",
                        
"no match here"
                    }
;
                
                
string sPattern = "cow";
                
                
foreach (string s in sentences){
                        System.Console.Write(
"{0,24}",s);
                        
                        
if (System.Text.RegularExpressions.Regex.IsMatch(s,sPattern,System.Text.RegularExpressions.RegexOptions.IgnoreCase)){
                                System.Console.WriteLine(
"  (math for '{0}' found)",sPattern);
                            }

                        
else{
                                System.Console.WriteLine();
                            }

                    }

            }

    }


以下代码是一个控制台应用程序,此程序使用正则表达式验证数组中每个字符串的格式。验证要求每个字符串具有电话号码的形式,即用短划线将数字分成三组,前两组个包含三个数字,第三组包含四个数字。这是通过正则表达式^//d{3}-//d{3}-//d{4}$完成的。

class  TestRegularExpressionValidation {
        
static void Main(){
                
string[] numbers = {
                        
"123-456-7890",
                        
"444-234-22450",
                        
"690-203-6578",
                        
"146-839-232",
                        
"146-839-2322",
                        
"4007-295-1111",
                        
"407-295-1111",
                        
"407-2-5555",
                    }
;
                
                
string sPattern = "^/d{3}-/d{3}-/d{4}$";
                
                
foreach (string s in numbers){
                        System.Console.Write(
"{0,14}",s);
                        
                        
if (System.Text.RegularExpressions.Regex.IsMatch(s,sPattern)){
                                System.Console.WriteLine(
" - valid");
                            }

                        
else{
                                System.Console.WriteLine(
" - invalid");
                            }

                    }

            }

    }


如何:联结多个字符串

有两种联结多个字符串的方法:使用String类重载的+运算符,以及使用StringBuilder类。+运算符使用方便,有助于生成直观的代码,但必须连续使用;每使用一次该运算符就创建一个新的字符串,因此将多个运算符串联的一起效率不高。例如:

string two = "two";

string str = "one " + two + " three";

System.Console.WriteLine(str);

尽管在代码中只出现了四个字符串,三个字符串联接在一起,最后一个字符串包含全部三个字符串,但总共要创建五个字符串,因为首先要将前面两个字符串联接,创建一个包含两个字符串的字符串。第三个字符串是单独追加的,形成存储在str中的最终字符串。

也可以使用StringBuilder类将每个字符串添加到一个对象中,然后由该对象通过一个步骤创建最终的字符串。下面的示例对此策略进行了演示。

示例

class  StringBuilderTest {
        
static void Main(){
                
string two = "two";
                
                System.Text.StringBuilder sb 
= new System.Text.StringBuilder();
                sb.Append(
"one ");
                sb.Append(two);
                sb.Append(
" three");
                System.Console.WriteLine(sb.ToString());
            }

    }


如何:修改字符串内容

字符串是不可变的,因此不能修改字符串的内容。但是,可以将字符串的内容提取到非不可变的窗体中,并对其进行修改,以形成新的字符串实例。

示例

下面的示例使用ToCharArray方法来将字符串的内容提取到char类型的数组中。然后修改此数组中的某些元素。之后,使用char数组创建新的字符串实例。

class  ModifyStrings {
        
static void Main(){
                
string str = "The quick brown fox jumped over the fence";
                System.Console.WriteLine(str);
                
                
char[] chars = str.ToCharArray();
                
int animalIndex = str.IndexOf("fox");
                
if (animalIndex != -1){
                        chars[animalIndex
++= 'c';
                        chars[animalIndex
++= 'a';
                        chars[animalIndex] 
= 't';
                    }

                
                
string str2 = new string(chars);
                System.Console.WriteLine(str2);
            }

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值