在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);
}
使用这些技巧可以更加优雅地处理字符串拆分操作,并且使代码更加清晰和易于维护。