在 C# 中,你可以将字符串视为字符数组,然而,更常见的做法是使用 string
关键字来声明一个字符串变量。string
关键字是 System.String
类的一个别名。
创建字符串对象
你可以使用以下几种方法之一来创建字符串对象:
-
-
-
-
-
通过调用格式化方法将值或对象转换为其字符串表示形式
以下示例演示了这一点:
using System;
namespace StringApplication {
class Program {
static void Main(string[] args) {
string fname, lname;
fname = "Rowan";
lname = "Atkinson";
char []letters= { 'H', 'e', 'l', 'l','o' };
string [] sarray={ "Hello", "From", "Tutorials", "Point" };
string fullname = fname + lname;
Console.WriteLine("Full Name: {0}", fullname);
string greetings = new string(letters);
Console.WriteLine("Greetings: {0}", greetings);
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);
}
}
}
当上述代码被编译和执行时,它产生以下结果:
Full Name: RowanAtkinson
Greetings: Hello
Message: Hello From Tutorials Point
Message: Message sent at 5:58 PM on Wednesday, October 10, 2012
字符串类的属性
String
类具有以下两个属性:
-
Chars
-
获取在当前
String
对象中指定位置的 Char
对象。
-
字符串类的方法
String
类有许多方法帮助你在工作中使用字符串对象。下表提供了一些最常见的方法:
下面列出了 String
类的一些方法。你可以访问 MSDN 库获取完整的方法列表和 String
类构造函数。
示例
比较字符串
using System;
namespace StringApplication {
class StringProg {
static void Main(string[] args) {
string str1 = "This is test";
string str2 = "This is text";
if (String.Compare(str1, str2) == 0) {
Console.WriteLine(str1 + " and " + str2 + " are equal.");
} else {
Console.WriteLine(str1 + " and " + str2 + " are not equal.");
}
Console.ReadKey() ;
}
}
}
当上述代码被编译和执行时,它产生以下结果:
This is test and This is text are not equal.
字符串包含字符串
using System;
namespace StringApplication {
class StringProg {
static void Main(string[] args) {
string str = "This is test";
if (str.Contains("test")) {
Console.WriteLine("The sequence 'test' was found.");
}
Console.ReadKey() ;
}
}
}
当上述代码被编译和执行时,它产生以下结果:
The sequence 'test' was found.
获取子字符串
using System;
namespace StringApplication {
class StringProg {
static void Main(string[] args) {
string str = "Last night I dreamt of San Pedro";
Console.WriteLine(str);
string substr = str.Substring(23);
Console.WriteLine(substr);
}
}
}
当上述代码被编译和执行时,它产生以下结果:
San Pedro
连接字符串
using System;
namespace StringApplication {
class StringProg {
static void Main(string[] args) {
string[] starray = new string[]{
"Down the way nights are dark",
"And the sun shines daily on the mountain top",
"I took a trip on a sailing ship",
"And when I reached Jamaica",
"I made a stop"};
string str = String.Join("\n", starray);
Console.WriteLine(str);
}
}
}
当上述代码被编译和执行时,它产生以下结果:
Down the way nights are dark
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop