Parsing a String (foreach)

Shaitan00

Junior Contributor
Joined
Aug 11, 2003
Messages
358
Location
Hell
Given a string called Format which would be of the form
string Format = “[Col1] : [Col2] : [Col3] : ……….. [ColX]”

I need to create a method to count the # of Columns the string defines [located between the [x]'s].

Any clues?
 
Last edited:
I would use the Split method of the string...
If you use it with the Char ":" it will create an array with all [x]'s, then you just have to "ask" the array how many object it has...

This will show a messagebox with the counting:
Visual Basic:
Dim a() As String = Format.Split(":")
MessageBox.Show(a.Length)

Alex :D
 
Last edited:
Amazing idea, that is exactly the type of method I needed [parsing was driving me nutz].

This is the code I am trying to use (given your example):
string[] arrCols = format.Split(" : ");


However it generates the following errors:
- The best overloaded method match for 'string.Split(params char[])' has some invalid arguments
- Argument '1': cannot convert from 'string' to 'char[]'


Any clues?
 
the parameter on the Split method can't be a string... it has the be a char ... and chars can't have more than 1 character...

use:
C#:
string[] arrCols = format.Split(":");

if you then want to take spaces use the Trim method on the string...


Alex :D
 
dynaimc_sysop, that will return a bunch of blank array elements,
because the string will be split at any one of those character.
So, for example, the array elements would be "", "Col1", " ", " ",
etc. I believe the best method is to use the Split method of the
Regex class.

C#:
string[] columns = System.Text.RegularExpressions.Regex.Split("[Col1] : [Col2] : [Col3] : [ColX]", " : ")

foreach (string column in columns) {
  // do whatever with column
}
 
Back
Top