您的位置:首页 > 编程语言 > C#

我的c#之路(5.字符串)

2014-05-20 23:20 134 查看
字符串 string

1.

--字符串是String类型的对象,它的值是文本。

--在内部,文本被存储为Char对象的顺序只读集合。

--C#字符串末尾没有以null结尾的字符;因此c#字符串可以包含任意数目的嵌入式null字符(“\0”)。

--字符串的Length属性代表它包含的Char对象的数量,而不是Unicode字符的数量。

2.

--声明和初始化字符串

string message1;

string message2=null;

string message3=System.String.Empty;     //等价于string message3=""

string oldPath="c:\\Program Files\\Microsoft Visual Studio 8.0";

string newPath=@"c:\Program Files\Microsoft Visual Studio 9.0";

System.String greeting="Hello World!";

var temp="I'm still a strongly-typed System.String!";

const string message4="You can't get rid of me!";

char[] letters={'A','B','C'};

string alphabet=new string(letters);    //除了在使用字符数组初始化字符串,不要使用new运算符创建字符串对象

3.

--string是引用类型,但定义相等运算符(==和!=)是为了比较string对象(而不是引用)的值:

string a="hello";

string b="h";

b+="ello";

Console.WriteLine(a==b);//True

Console.WriteLine((object)a==(object)b);//False

--+运算符用于连接字符串:

string a="good"+"morning";

4.

--字符串对象是不可变的:即它们创建之后就无法更改。所有看似修改字符串的String方法和c#运算符实际上都以新字符串对象的形式返回结果。

--当连接s1和s2的内容以形成一个字符串时,不会修改两个原始字符串。+=运算符会创建一个包含组合内容的新字符串。这个新对象赋给变量s1,而最初赋给s1的对象由于没有其他任何变量包含对它的引用而释放,用于垃圾回收。

string s1="A string is more ";

string s2="than the sum of its chars.";

s1+=s2;

System.Console.WriteLine(s1);

//Output:A string is more than the sum of its chars.

--由于“修改“字符串实际上是创建新字符串,因此创建对字符串的引用时必须谨慎。如果创建了对字符串的引用,然后”修改“原始字符串,则该引用指向的仍是原始对象,而不是修改字符串时创建的新对象。

string s1=”Hello ";

string s2=s1;

s1+="World";

System.Console.WriteLine(s2);

//Output:Hello

5.

--正则字符串(字符串文本可包含任何字符。包括转义序列)

string a="\\\u0066\n";

Console.WriteLine(a);

--格式字符串(格式字符串是内容可以在运行时动态确定的一种字符串)

System.String.Format("{0} times {1}={2}",i,j,(i*j));

--原义字符串(以@开头并且也用双引号引起来)

@"c:\Docs\Source\a.txt“    //同”c:\\Docs\\Source\\a.txt"

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

等价于:

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

若要在一个用@引起来的字符串中包括一个双引号,请使用两对双引号:

@"“”Ahoy!"" cried the captain."  //即"Ahoy!" cried the captain.

6.

--空字符串

string s=String.Empty;//或者 string s="";

--Null字符串

string s=null;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string str = "hello";
string nullStr = null;
string emptyStr = String.Empty;
//
string tempStr = str + nullStr;
//The following line displays "hello."
Console.WriteLine(tempStr);
//
bool b = (emptyStr == nullStr);
//The following line displays False.
Console.WriteLine(b);
//
//The following line creates a new empty string.
string newStr = emptyStr + nullStr;
//
//Null strings and empty strings behave differently.The following
//two lines display 0.
Console.WriteLine(emptyStr.Length);
Console.WriteLine(newStr.Length);
//The following line raises a NullReferenceException.
//Console.WriteLine(nullStr.Length);
//
//The null character can be displayed and counted,like other chars.
string s1 = "\x0" + "abc";
string s2 = "abc" + "\x0";
//The following line displays "* abc*"
Console.WriteLine("*"+s1+"*");
//The following line displays "*abc *"
Console.WriteLine("*"+s2+"*");
//The following line displays 4.
Console.WriteLine(s2.Length);
}
}
}

7.
--可以使用带索引值的数组表示法获取对各个字符的只读访问

string s5="Printing backwards";

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

{

System.Console.WriteLine(s5[s5.Length-i-1]);

}

//Output:"sdrawkcab gnitnirP"

8.

--c#内置数据类型都提供了ToString方法,用于将值转换为字符串。此方法可以用于将数值转换为字符串

int year=1999;

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

System.Console.WriteLine(msg);

//Outputs "Eve was born in 1999"

9.

Substring()

--子字符串从指定的字符位置开始且具有指定的长度

string s3="Visual C# Express";

System.Console.WriteLine(s3.Substring(7,2));

//Output:"C#"

Replace()

--所有的指定字符替换为其他指定字符

System.Console.WriteLine(s3.Replace("C#","Basic"));

//Output:"Visual Basic Express"

Trim()

--移除所有前导空白字符和尾部空白字符

string s3="     Visual C# Express       ";

System.Console.WriteLine(s3.Trim());

//Output:" Visual C# Express "

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"

CompareTo()

--用于根据一个字符串是小于(<)还是大于(>)另一个字符串来返回一个整数值。

比较字符串时使用的是Unicode值,并且小写的值小于大写的值。

string string1 = "abc";

string string2 = "ABC";

int result2 = string1.CompareTo(string2);

if (result2 < 0)

 {

      System.Console.WriteLine("{0} is less than {1}",string1,string2);

 }

//Output::abc is less than ABC

IndexOf()

--在一个字符串中搜索另一个字符串。(类似LastIndexOf、StartsWith和EndsWith)

如果未找到搜索字符串,IndexOf()返回-1;否则,返回它出现的第一个位置的索引(从0开始)。IndexOf方法区分大小写,并使用当前区域性。

string s3="Visual C# Express";

int index=s3.IndexOf("C");

//index=7

Split()

--将字符串拆分为子字符串

使用分隔符(如空格字符)char数组,并返回一个子字符串数组

可以通过foreach访问此数组

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string words = "This is a list of words,with: a bit of punctuation" + "\tand a tab character.";
string[] split = words.Split(new Char[]{' ',',','.',':','\t'});
foreach (string s in split)
{
if (s.Trim() != "")
{
Console.WriteLine(s);
}
}
System.Console.ReadKey();
}
// The
4000
example displays the following output to the console:
// This
// is
// a
// list
// of
// words
// with
// a
// bit
// of
// punctuation
// and
// a
// tab
// character
}
}

String.Concat()
--连接指定的String数组的元素,连接String的两个指定实例。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] s = { "hello ","and ","welcome ","to ","this ","demo!"};
Console.WriteLine(string.Concat(s));
Array.Sort(s);
Console.WriteLine(string.Concat(s));
System.Console.ReadKey();
}
//Output:
//hello and welcome to this demo!
//and demo!hello this to welcome
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string fName = "Simon";
string mName = "Jake";
string lName="Harrows";
mName=" "+mName.Trim();
lName = " " + lName.Trim();
Console.WriteLine("Welcome to this page,'{0}'!",string.Concat(string.Concat(fName,mName),lName));
System.Console.ReadKey();
}
//Output:
//Welcome to this page,'Simon Jake Harrows'!
}
}


10.
--字符串对象不可变,因此一旦创建就不能更改。对字符串进行操作的方法实际会返回新的字符串对象。因此,出于性能方面的考虑,大量连接或其他涉及的字符串操作应通过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();

//Outputs Cat:the ideal pet

string question="hOW DOES mICROSOFT wORD DEAL WITH THE cAPS lOCK KEY?";

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

for(int j=0;j<sb.Length;j++)

{

if(System.Char.IsLower(sb[j]==true)

sb[j]=System.Char.ToUpper(sb[j]);

else if(System.Char.IsUpper(sb[j]==true)

sb[j]=System.Char.ToLower(sb[j]);

}

//Store the new string

string corrected=sb.ToString();

System.Console.WriteLine(corrected);

//Output:How does Microsoft Word deal with the Caps Lock key?

11.

--搜索字符串:

使用IndexOf、LastIndexOf、StartsWith和EndsWith方法搜索字符串。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string str = "Extension methods have all the capabilities of regular static methods.";

System.Console.WriteLine("\"{0}\"",str);
bool test1 = str.StartsWith("extension");
System.Console.WriteLine("Starts with \"extension\"?{0}",test1);
bool test2 = str.StartsWith("extension", System.StringComparison.CurrentCultureIgnoreCase);
System.Console.WriteLine("Starts with \"extension\"?{0}(ignoring case)", test2);
bool test3 = str.EndsWith(".",System.StringComparison.CurrentCultureIgnoreCase);
System.Console.WriteLine("Ends with '.'?{0}",test3);
int first = str.IndexOf("methods") + "methods".Length;
int last = str.LastIndexOf("methods");
string str2 = str.Substring(first,last-first);
System.Console.WriteLine("Substring between \"methods\" and \"methods\":'{0}",str2);
//Keep the console window open in debug mode
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
/*
Output:
"Extension methods have all the capabilities of regular static methods."
Starts with "extension"? False
Starts with "extension"? True (ignoring case)
Ends with '.'? True
Substring between "methods" and "methods": ' have all the capabilities of regular static '
Press any key to exit.
*/
}
}

串联字符串:
可以使用+或+=运算符,也可以使用String.Concat、String.Format或StringBuilder.Append方法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string text = null;
//Use StringBuilder for concatenation in tight loops
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < 100; i++)
{
sb.AppendLine(i.ToString());//将默认的行终止符追加到当前StringBuilder对象的末尾
}
System.Console.WriteLine(sb.ToString());
//Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
/*
Output:
* 0
* 1
* 2
* 3
* 4
* 5
* ...
* 99
*/
}
}

比较字符串:
(略)

拆分字符串:

使用String.Split方法分析字符串

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
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);
}
//Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
/* Output:
Original text: 'one two three:four,five six seven'
7 words in text:
one
two
three
four
five
six
seven
*/
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c#