c#中处理字符串常用的函数及方法详细说明

一、string关键字与StringBuilder类

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

string s = "Hello, World!";

字符串对象是“不可变的”,即它们一旦创建就无法更改。对字符串进行操作的方法实际上返回的是新的字符串对象。因此,出于性能方面的原因,大量的连接或其他涉及字符串的操作应当用 StringBuilder 类执行,如下所示:

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

sb.Append("one ");

sb.Append("two ");

sb.Append("three");

string str = sb.ToString();

二、字符串使用

1、转移字符“/”

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

如果希望包含反斜杠,则它前面必须还有另一个反斜杠,如“//”。

2、“@”符号

@ 符号会告知字符串构造函数忽略转义符和分行符。

因此,以下两个字符串是完全相同的:

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

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

3、ToString()

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

int year = 1999;

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

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

   另外,可以通过参数格式化ToString()的显示输出。如,对于时间类型格式,可以通过ToString()方法自定义时间显示格式。如:

System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

//outputs "2009-03-11 18:05:16.345"

//"MM":指定月份为2位字符串,不足2位则前方补"0";"M":为月份数值转换的字符串;

//"HH":表示24小时制的小时;"hh"表示12小时制的小时;

4、SubString()

格式:Substring(int startindex, int len)

用于获取源字符串指定起始位置startindex,指定长度len的字符串。

参数Startindex索引从0开始,且最大值必须小于源字符串的长度,否则会编译异常;

参数len的值必须不大于源字符串索引指定位置开始,之后的字符串字符总长度,否则会出现异常;

示例:

string s4 = "Visual C# Express";

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

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

5、Replace()

格式:Replace(string oldValue, string newValue)

用于字符串中特定字符串组合的替换,即将源字符串中的所有oldValue 字符串替换为 newValue 字符串。

示例:

string s5 = "Visual C# Express";

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

6、Split()

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

示例:

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

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

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

{

System.Console.WriteLine(substr);

}

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

The

cat

sat

on

the

mat.

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

示例:

class TestStringSplit

{

static void Main()

{

char[] delimiterChars = { ' ', ',', '.', ':', '/t' };

 

string text = "one/ttwo 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);

}

}

}

输出:

Original text: 'one two three:four,five six seven'

7 words in text:

one

two

three

four

five

six

seven

另外,还可通过正则表达式Regex.Split()的方法,通过字符串分隔字符串。

示例:

using System.Text.RegularExpressions; //需要引用正则表达式的命名空间

string str="aaajsbbbjsccc";

string[] sArray=Regex.Split(str,"js",RegexOptions.IgnoreCase); //正则表达式

// RegexOptions.IgnoreCase 表示忽略字母大小写

foreach (string i in sArray) Response.Write(i.ToString() + "<br>");

输出:

aaa

bbb

ccc

7、Trim()

Trim() 从当前 String 对象移除所有前导空白字符和尾部空白字符。

示例:

string s7 = " Visual C# Express ";

System.Console.WriteLine(s7); // outputs " Visual C# Express "

System.Console.WriteLine(s7.Trim()); // outputs "Visual C# Express"

8、ToCharArray()

格式:ToCharArray(int startindex,int len)

用于将字符复制到字符数组。

示例:

string s8 = "Hello, World";

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

foreach (char c in arr)

{

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

}

 

示例:修改字符串内容

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

下面的示例使用 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);

}

}

输出:

The quick brown fox jumped over the fence

The quick brown cat jumped over the fence

9、利用索引访问字符串中的各个字符

格式:str[int index]

示例:逆序排列字符串

string s9 = "Printing backwards";

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

{

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

}

10、更改大小写,ToUpper() 和 ToLower()

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

string s10 = "Battle of Hastings, 1066";

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

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

 

 

 

11、比较

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

string color1 = "red";

string color2 = "green";

string color3 = "red";

if (color1 == color3)

{

System.Console.WriteLine("Equal");

}

if (color1 != color2)

{

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

}

 

 

12、CompareTo()

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

示例:

string s121 = "ABC";

string s122 = "abc";

if (s121.CompareTo(s122) > 0)

{

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

}

else

{

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

}

 

 

13、字符串索引

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

示例:

string s13 = "Battle of Hastings, 1066";

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

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

 

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

示例:

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

}

}

 

输出:

'A silly sentence used for silly purposes.'

starts with 'a silly'? False

starts with 'a silly'? True (ignore case)

ends with '.'? True

between two 'silly' words: 'silly sentence used for '

三、使用 StringBuilder

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

示例:

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

sb[0] = 'C';

System.Console.WriteLine(sb.ToString()); // displays Cat: the ideal pet

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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

厦门德仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值