在 C# 中,您可以使用字符數組來表示字符串,但是,更常見的做法是使用 string 關鍵字來聲明一個字符串變量。string 關鍵字是 System.String 類的別名。
您可以使用以下方法之一來創建 string 對象:
下面的實例演示了這點:
using System;
namespace StringApplication
{
class Program
{
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() ;
}
}
}
當上面的代碼被編譯和執行時,它會產生下列結果:
Full Name: RowanAtkinson Greetings: Hello Message: Hello From Tutorials Point Message: Message sent at 17:58 on Wednesday, 10 October 2012
String 類有以下兩個屬性:
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);
Console.ReadKey() ;
}
}
}
運行實例 »
當上面的代碼被編譯和執行時,它會產生下列結果:
Last night I dreamt of San Pedro 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);
Console.ReadKey() ;
}
}
}
當上面的代碼被編譯和執行時,它會產生下列結果:
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