根据位置c#划分字符串

时间:2014-12-05 10:27:28

标签: c# string split delimiter

我有以下字符串,例如

PT01 0200LB  Wax  N011 00000000500030011 00000000

我需要根据以下条件获取单独的字符串

Position    Description

1-2         Catagory Type
3-6         Action Type
7-15        Kit Number

我需要根据这些位置获取每个字符串。 我该怎么办?

5 个答案:

答案 0 :(得分:2)

我不知道它是否正是你想要的,因为没有根据你的例子发布精确的预期结果,但这应该是正确的方向:

public class CustomObject
{
    public string CategoryType { get; set; }
    public string ActionNumber { get; set; }
    public string KitNumber { get; set; }
}
//create Dummy Data
var source = new List<string>()
{
    "PT01 0200LB  Wax  N011 00000000500030011 00000000",
    "PT02 0300LB  Bee  C011 00000000500030011 00000000",
    "PT03 0300LB  Silk  A011 00000000500030011 00000000",
    "PT04 0400LB  Cornflakes  A011 00000000500030011 00000000"
};

var result = from s in source
             select new CustomObject {
                CategoryType = s.Substring(0,2),
                ActionNumber = s.Substring(2,3),
                //read to end
                KitNumber = s.Substring(5, s.Length -6)
             };

输出:

enter image description here

答案 1 :(得分:1)

您可以使用子字符串或下载一些现成的工具,如

http://www.filehelpers.net/

它有解析Fixed Length文件的类 单击主页上的“快速启动固定长度记录”

并按如下方式使用

[FixedLengthRecord()] 
public class Record
{ 
    [FieldFixedLength(2)] 
    public int CategoryType; 

    [FieldFixedLength(3)] 
    [FieldTrim(TrimMode.Right)] 
    public string ActionType; 

    [FieldFixedLength(7)] 
    [FieldTrim(TrimMode.Right)]
    public string KitNumber; 
 }

稍后在你的代码中

var engine = new FileHelperEngine<Record>();
Record[] res = engine.ReadFile("FileIn.txt");

答案 2 :(得分:1)

让我们将头寸转换为从零开始的指数(pos1-1)和长度(pos2-pos1 + 1):

Position    Description     Index  Length

1-2         Catagory Type   0      2
3-6         Action Type     2      4
7-15        Kit Number      6      9

现在,您可以在Substring方法中使用它来获取字符串的一部分。例如:

string actionType = input.Substring(2, 4);

您可能希望修剪某些子字符串中的空格。例如:

string actionType = input.Substring(2, 4).Trim();

答案 3 :(得分:1)

除了其他优秀的答案外,还有很多方法可以执行此操作。

通过扩展方法

/// <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));

通过RegularExpressions

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的回答中使用了简洁的方法。

答案 4 :(得分:0)

我认为你想使用C#Substring?

string splitStr = Yourstr.Substring(0,2);

Msdn:Substring