问题描述
|
我在这里遇到了一个小问题,我正在寻找分割字符串的更好方法。
例如,我收到一个看起来像这样的字符串。
0000JHASDF+4429901234ALEXANDER
我知道字符串建立的模式,我有一个像这样的数字数组。
4,5,4,7,9
0000 - JHASDF - +442 - 9901234 - ALEXANDER
使用String MID命令将整个内容拆分很容易,但是当我收到包含8000-10000个数据集的文件时,这似乎很慢。
所以有什么建议可以使我更快地获取列表或字符串数组中的数据吗?
如果有人知道如何执行此操作,例如使用RegEx。
解决方法
var lengths = new[] { 4,6,4,7,9 };
var parts = new string[lengths.Length];
// if you\'re not using .NET4 or above then use ReadAllLines rather than ReadLines
foreach (string line in File.ReadLines(\"YourFile.txt\"))
{
int startPos = 0;
for (int i = 0; i < lengths.Length; i++)
{
parts[i] = line.Substring(startPos,lengths[i]);
startPos += lengths[i];
}
// do something with \"parts\" before moving on to the next line
}
, 是不是VB方法?
string firstPart = string.Substring(0,4);
string secondPart = string.Substring(4,5);
string thirdPart = string.Substring(9,4);
//...
, 也许是这样的:
string[] SplitString(string s,int[] parts)
{
string[] result=new string[parts.Length];
int start=0;
for(int i=0;i<parts.Length;i++)
{
int len=parts[i];
result[i]=s.SubString(start,len);
start += len;
}
if(start!=s.Length)
throw new ArgumentException(\"String length doesn\'t match sum of part lengths\");
return result;
}
(我没有编译它,所以它可能包含一些小错误)
, 由于Mid()
函数是VB,因此您可以尝试
string.Substring(0,4);
等等。
, 我知道这很晚了,但是在Microsoft.VisualBasic.FileIO命名空间中,您可以找到textfieldparser,这样可以更好地处理您的问题。这是指向MSDN的链接-https://msdn.microsoft.com/zh-cn/library/zezabash.aspx,并附有说明。该代码在VB中,但是您可以轻松地将其转换为C#。您还需要添加对Microsoft.VisualBasic.FileIO命名空间的引用。希望这对将来在这个问题上绊脚石的人有所帮助。
这是vb中发问者问题的外观:
Using Reader As New Microsoft.VisualBasic.FileIO.
TextFieldParser(\"C:\\TestFolder\\test.log\")
Reader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(4,9)
Dim currentRow As String()
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox(\"Line \" & ex.Message &
\"is not valid and will be skipped.\")
End Try
End While
End Using
, 正则表达式拆分方法是可能的,但是由于您在字符串中没有特定的定界符,因此我怀疑它是否有用,并且不可能更快。
String.Substring也有可能。您可以这样使用:var myFirstString = fullString.Substring(0,4)