基本概念
字符串是一种用于表示文本序列的数据类型。字符串是由字符组成的不可变对象,这意味着一旦创建了一个字符串,你就不能改变它的内容。
常用字符串方法
Length:获取字符串长度
string str = "Hello";
Console.WriteLine(str.Length); // 输出: 5
Substring:返回从指定索引开始的子字符串
string str = "Hello World";
string subStr = str.Substring(6);
Console.WriteLine(subStr); // 输出: "World"
Concat:将两个或多个字符串连接在一起
string result = string.Concat("Hello", " ", "World");
Console.WriteLine(result); // 输出: "Hello World"
Format:格式化字符串
string formattedString = string.Format("{0} {1}", "Hello", "World");
Console.WriteLine(formattedString); // 输出: "Hello World"
Join:将字符串数组连接成一个字符串,以指定的分隔符分隔
string[] words = { "Hello", "World" };
string joinedString = string.Join(", ", words);
Console.WriteLine(joinedString); // 输出: "Hello, World"
Replace:替换字符串中的子字符串
string originalString = "Hello World";
string replacedString = originalString.Replace("World", "Universe");
Console.WriteLine(replacedString); // 输出: "Hello Universe"
Split:将字符串分割成子字符串数组
string sentence = "Hello World from CSharp";
string[] words = sentence.Split(' ');
foreach (string word in words)
{
Console.Write(word);
}
// 输出:HelloWorldfromCSharp
Contains:检查字符串是否包含指定的子字符串
string str = "Hello World";
bool containsWorld = str.Contains("World");
Console.WriteLine(containsWorld); // 输出: True
ToLower / ToUpper:转换字符串的大小写
string str = "Hello World";
string lowerCaseStr = str.ToLower();
string upperCaseStr = str.ToUpper();
Console.WriteLine(lowerCaseStr); // 输出: "hello world"
Console.WriteLine(upperCaseStr); // 输出: "HELLO WORLD"
Compare / CompareTo:比较两个字符串
string str1 = "Hello";
string str2 = "World";
int comparisonResult = str1.CompareTo(str2);
Console.WriteLine(comparisonResult < 0); // 输出: True
Equals / ReferenceEquals:检查两个字符串是否相等
string str1 = "Hello";
string str2 = "Hello";
bool areEqual = string.Equals(str1, str2);
Console.WriteLine(areEqual); // 输出: True
代码示例
static void Main(string[] args)
{
//字符串,字符串连接
string fname, lname;
fname = "Rowan";
lname = "Atkinson";
string fullname = fname + lname;
Console.WriteLine("Full Name: {0}", fullname);
//通过使用 string 构造函数
char[] letters = { 'H', 'e', 'l', 'l','o' };
string greetings = new string(letters);
Console.WriteLine("Greetings: {0}", greetings);
//方法返回字符串
string[] sarray = { "Hello", "From", "Tutorials", "Point" };
string message = String.Join(" ", sarray);
Console.WriteLine("Message: {0}", message);
//用于转化值的格式化方法
DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
string chat = String.Format("Message sent at {0:t} on {0:D}",
waiting);
Console.WriteLine("Message: {0}", chat);
Console.ReadKey() ;
}