Separation of lines in certain positions

I have a little problem here, I'm looking for a better way to split Strings. For example, I get a line that looks like this.

0000JHASDF+4429901234ALEXANDER

I know the pattern with which the string is built, and I have an array of numbers like this.

4,5,4,7,9
0000 - JHASDF - +442 - 9901234 - ALEXANDER

It's easy to split all of this into a String MID command, but it seems to be slow when I get a file containing 8000 - 10000 datasets. So, any suggestion, how can I do this faster to get the data in a list or in an array of strings? If someone knows how to do this, for example, with RegEx.

+3
source share
6 answers
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
}
+8
source

Isn't that a VB method?

string firstPart = string.Substring(0, 4);
string secondPart = string.Substring(4, 5);
string thirdPart = string.Substring(9, 4);
//...
+5
source

, - :

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;
}

( , , , )

+2

, , Microsoft.VisualBasic.FileIO , . MSDN - https://msdn.microsoft.com/en-us/library/zezabash.aspx . VB, #. 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  
+1

Regex Split Method , , , .

String.Substring is also an option. You use it like:var myFirstString = fullString.Substring(0, 4)

0
source

Since the function Mid()is VB, you can just try

string.Substring(0, 4);

etc.

0
source

All Articles