除了其他出色的答案之外,还有很多方法可以执行此操作。
通过扩展方法
/// <summary>Splits the specified string at the specified indexes.</summary>
/// <param name="str">The string to split.</param>
/// <param name="delimiters">The delimiters / Indexes to split by.</param>
/// <returns>A <see cref="T:System.string[]" /> array containing the split result.</returns>
public static string[] Split(this string str, params int[] delimiters) {
return delimiters.Select(
(offset, argIndex) =>
str.Substring(
offset,
(argIndex < delimiters.Length - 1
? delimiters[argIndex + 1] - offset
: str.Length - offset)))
.ToArray();
}
用法
[TestMethod]
public void SplitByDelimitersTest() {
// Replace the spaces in this string, it makes it possible to get the data using the extension method.
var data = "PT01 0200LB Wax N011 00000000500030011 00000000".Replace(" ", "");
var result = data.Split(0, 2, 8);
var expected = new[] { "PT", "010200", "LBWaxN0110000000050003001100000000" };
CollectionAssert.AreEqual(expected, result, "Collections were not equal in the SplitByDelimeters test.");
}
通过 String.Split
var data = "PT01 0200LB Wax N011 00000000500030011 00000000";
// If you want the extra empty spcaces around "Wax" removed, simply specify StringSplitOptions.RemoveEmptyEntries instead.
var split = data.Split(new [] {" "}, StringSplitOptions.None);
var categoryType = split[0];
var actionNumber = split[1];
var kitNumber = String.Join(" ", split.Skip(2));
通过正则表达式
var data = "PT01 0200LB Wax N011 00000000500030011 00000000";
var match = Regex.Match(data, @"(?<categoryType>..\d\d) (?<actionNumber>\d{4}..) (?<kitNumber>.+)");
var categoryType = match.Groups["categoryType"].Value;
var actionNumber = match.Groups["actionNumber"].Value;
var kitNumber = match.Groups["kitNumber"].Value;
我相信还有更多方法可以做到这一点,可能有一些使用 Serv 回答中的简洁方式。