在 C# 中按字符串拆分字符串
Harshit Jindal
2023年10月12日
Csharp
Csharp String
Strings 是用于存储文本数据的对象。C# System.String 库提供了许多用于操作、创建和比较字符串的方法。
我们经常遇到的一种常见情况是拆分字符串以提取一些重要数据。本文将重点介绍使用另一个 string 拆分 string 以及在 C# 中执行此操作的不同方法。
在 C# 中使用 String.Split() 方法
String.Split() 方法具有不同的重载,为我们提供了拆分 string 的不同方法。
我们对一个特殊的重载感兴趣,它接受一个 string 作为参数,并使用它作为分隔符将给定的 string 拆分为其子字符串。
using System;
public class Example {
public static void Main() {
string str = "Delft@@Stack";
string separator = "@@";
string[] tokens = str.Split(new string[] { separator }, StringSplitOptions.None);
Console.WriteLine(String.Join(" ", tokens));
}
}
输出:
Delft Stack
在上述方法中,我们使用分隔符字符串@@将给定字符串拆分为子字符串数组,然后通过将它们与空格连接来打印。
在 C# 中使用 Regex.Split() 方法
Regex.Split() 方法可以实现我们想要实现的目标。它获取输入字符串并根据正则表达式条件匹配将其拆分为子字符串数组。
using System;
using System.Text.RegularExpressions;
public class Program {
public static void Main() {
string str = "Delft@@Stack";
string separator = "@@";
string[] tokens = Regex.Split(str, separator);
Console.WriteLine(String.Join(" ", tokens));
}
}
输出:
Delft Stack
从上面的代码示例中可以看出,Regex.Split() 方法的用法比 String.Split() 方法更简单。它的执行速度更快,效率更高。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Harshit Jindal
Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.
LinkedIn