我有一个固定长度的字符串,必须在字符串的可变位置拆分以产生子字符串。
30849162 AUF3063100-2022031Doe Deanne 2610194031482100720081007200820000000000G43Z4206372 10 8 98282000000000911140000 00000000K6358Z8643K638 D126 Z099 320930090308009251519 132093 100720080071 0000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000 00000000
列断点是: 15,18,33,61,81,89,93,94,102,110,111,114,118,
有谁知道我该怎么做?我有数千行解析
答案 0 :(得分:2)
将断点放在一个数组中,并在循环中使用.substring()
来表示这些数字。这大致是您想要的方式,但您必须对其进行调整以准确补偿您希望列中断的位置。
int[] nums = {0, 15, 18, 33, 61, 81, 89, 93, 94, 102, 110, 111, 114, 118 };
string input = "Long string here";
for (int i = 0; i < nums.Length - 1; i++)
{
Console.WriteLine(input.Substring(nums[i], nums[i + 1] - nums[i]));
}
答案 1 :(得分:1)
或者你可以使用一些讨厌的LINQ ..
public string[] ReturnMyStrings(string str)
{
int[] br = { 15, 18, 33, 61, 81, 89, 93, 94, 102, 110, 111, 114, 118 };
return br.Select((x, i) =>
str.Substring(br.ElementAtOrDefault(i - 1), x - br.ElementAtOrDefault(i - 1)))
.ToArray();
}
答案 2 :(得分:0)
如果你想让你的代码可扩展,你可以实现一些类来完成这项工作。
static void Main(string[] args)
{
string inputString = "30849162 AUF3063100-2022031Doe Deanne " +
"2610194031482100720081007200820000000000G43Z4" +
"206372 10 8 98282000000000911140000 00000000K" +
"6358Z8643K638 D126 Z099 320930090308009251519" +
"132093 100720080071 0000000000000000000000000" +
"000000000000000000000000000000000000000000000" +
"002022031 00000000000000000000000000000000000" +
"0000000000 00000000";
//myRecord will hold the entire input in its split form
var myRecord = new StringSplitterRecord()
{
fields = new List<StringSplitterField>()
{
//define all the different fields
new StringSplitterField(inputString, 0, 15, "Name of field 1"),
new StringSplitterField(inputString, 15, 3, "Name of field 2"),
new StringSplitterField(inputString, 18, 15, "Name of field 3"),
new StringSplitterField(inputString, 33, 28, "Name of field 4"),
new StringSplitterField(inputString, 61, 20, "Name of field 5"),
new StringSplitterField(inputString, 81, 8, "Name of field 6"),
new StringSplitterField(inputString, 93, 1, "Name of field 7"),
new StringSplitterField(inputString, 94, 8, "Name of field 8"),
new StringSplitterField(inputString, 102, 8, "Name of field 9"),
new StringSplitterField(inputString, 110, 1, "Name of field 10"),
new StringSplitterField(inputString, 111, 3, "Name of field 11"),
new StringSplitterField(inputString, 114, 4, "Name of field 12"),
}
};
}
class StringSplitterRecord
{
public List<StringSplitterField> fields;
}
class StringSplitterField
{
private string _contents;
private string _fieldType;
public StringSplitterField(string originalString, int startLocation, int length, string fieldType)
{
_contents = originalString.Substring(startLocation, length);
_fieldType = fieldType;
}
}
这不仅会将输入字符串拆分为需要的部分,而且会将它们全部放在一个列表中,每个子部分都有一个名称。然后,您可以使用LINQ等来检索所需的数据。