在特定位置分割字符串
我在这里遇到了一些问题,我正在寻找更好的方法来分割字符串。 例如,我收到一个像这样的字符串。在特定位置分割字符串
0000JHASDF+44299ALEXANDER
我知道字符串构建模式,我有这样的数组数组。
4,5,4,7,9
0000 - JHASDF - +442 - 99- ALEXANDER
这是很容易使用String MID命令分割了整个事情了,但它似乎当我收到包含8000点文件是缓慢的 - 10000的数据集。 因此,任何建议我如何能更快地获取列表或字符串数组中的数据? 如果有人知道如何使用RegEx执行此操作。
Regex Split Method将是一种可能性,但由于在字符串中没有特定的分隔符,因此我怀疑它会有什么用处,而且不太可能会更快。
String.Substring也是一种可能性。您可以使用它像:var myFirstString = fullString.Substring(0, 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;
}
(我没编译它,所以它可能包含一些小错误)
是不是中旬VB方法?
string firstPart = string.Substring(0, 4);
string secondPart = string.Substring(4, 5);
string thirdPart = string.Substring(9, 4);
//...
由于Mid()
功能是VB,你可以简单地尝试
string.Substring(0, 4);
等。
我知道,仍然有点困惑VB.net/C#编程有一个在工作,一个在家。 :P – Lim 2011-05-31 09:43:36
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
}
我知道这是晚了,但在Microsoft.VisualBasic.FileIO命名空间中,你可以找到使用TextFieldParser,它会做的更好处理您的问题。这里是一个链接到MSDN - https://msdn.microsoft.com/en-us/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, 6, 4, 7, 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'是要走的路,它肯定不会使用正则表达式会更快... – 2011-05-31 09:26:07
BTW ,你的数字是错误的,它应该是4,6,4,7,9(JHASDF是6个字符,而不是5) – 2011-05-31 09:35:31