在C#中使用Split方法可以很容易地將一個字符串按照指定的分隔符拆分成多個子字符串。以下是一些優雅地使用Split方法的示例:
string str = "apple,banana,cherry";
string[] fruits = str.Split(',');
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
string str = "apple;banana,cherry";
char[] separators = { ',', ';' };
string[] fruits = str.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
string str = " apple , banana , cherry ";
char[] separators = { ',' };
string[] fruits = str.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (string fruit in fruits)
{
Console.WriteLine(fruit.Trim());
}
string str = "apple,,banana,,cherry";
char[] separators = { ',' };
string[] fruits = str.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
使用這些技巧可以更加優雅地處理字符串拆分操作,并且使代碼更加清晰和易于維護。