Splitting a String

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Materialised

    Splitting a String

    Hi all,

    Just wondering if someone could help me with this little problem I'm having.

    I have a string value (it actually represents a barcode) which looks
    like this:

    5021378002392

    What I wish to do is split this string in 4 different string values, as
    such:

    val1 = 50;
    val2 = 21378;
    val3 = 00239;
    val4 = 2;

    The placement of the values is actually fixed, so it will always be 2,5,5,1.
    Does anyone Know how i can do this?
  • Nicholas Paldino [.NET/C# MVP]

    #2
    Re: Splitting a String

    Materialised,

    Why not just do this?

    public static int[] SplitBarCode(st ring barcode)
    {
    // The return value.
    int[] retVal = new int[4];

    // Split the string.
    retVal[0] = Int32.Parse(bar code.Substring( 0, 2));
    retVal[1] = Int32.Parse(bar code.Substring( 2, 5));
    retVal[2] = Int32.Parse(bar code.Substring( 7, 5));
    retVal[3] = Int32.Parse(bar code.Substring( 12, 1));

    // Return the value.
    return retVal;
    }

    Of course, you might want to put a little more error handling into this,
    but this should do it.

    Hope this helps.


    --
    - Nicholas Paldino [.NET/C# MVP]
    - mvp@spam.guard. caspershouse.co m


    "Materialis ed" <materialised@p rivacy.net> wrote in message
    news:4d75icF17s v83U1@individua l.net...[color=blue]
    > Hi all,
    >
    > Just wondering if someone could help me with this little problem I'm
    > having.
    >
    > I have a string value (it actually represents a barcode) which looks like
    > this:
    >
    > 5021378002392
    >
    > What I wish to do is split this string in 4 different string values, as
    > such:
    >
    > val1 = 50;
    > val2 = 21378;
    > val3 = 00239;
    > val4 = 2;
    >
    > The placement of the values is actually fixed, so it will always be
    > 2,5,5,1.
    > Does anyone Know how i can do this?[/color]


    Comment

    • Ludwig

      #3
      Re: Splitting a String

      On Fri, 19 May 2006 20:33:29 -0400, "Nicholas Paldino [.NET/C# MVP]"
      <mvp@spam.guard .caspershouse.c om> wrote:
      [color=blue]
      >Materialised ,
      >
      > Why not just do this?
      >
      >public static int[] SplitBarCode(st ring barcode)
      >{
      > // The return value.
      > int[] retVal = new int[4];
      >
      > // Split the string.
      > retVal[0] = Int32.Parse(bar code.Substring( 0, 2));
      > retVal[1] = Int32.Parse(bar code.Substring( 2, 5));
      > retVal[2] = Int32.Parse(bar code.Substring( 7, 5));
      > retVal[3] = Int32.Parse(bar code.Substring( 12, 1));
      >
      > // Return the value.
      > return retVal;
      >}
      >
      > Of course, you might want to put a little more error handling into this,
      >but this should do it.
      >
      > Hope this helps.[/color]

      Use regular expression (RegEx class) and its Split method!.
      --
      Ludwig Stuyck

      Comment

      • Mark Rae

        #4
        Re: Splitting a String

        "Ludwig" <none@none.co m> wrote in message
        news:ppvt62149e 2bb47ttv4qdkmi9 9uocrifpg@4ax.c om...
        [color=blue]
        > Use regular expression (RegEx class) and its Split method!.[/color]

        How could you use that in this case...?


        Comment

        • Ludwig

          #5
          Re: Splitting a String

          On Sat, 20 May 2006 13:19:28 +0100, "Mark Rae"
          <mark@markN-O-S-P-A-M.co.uk> wrote:
          [color=blue]
          >"Ludwig" <none@none.co m> wrote in message
          >news:ppvt62149 e2bb47ttv4qdkmi 99uocrifpg@4ax. com...
          >[color=green]
          >> Use regular expression (RegEx class) and its Split method!.[/color]
          >
          >How could you use that in this case...?
          >[/color]

          Out of my head:
          string[] parts = Regex.Split("50 21378002392",
          @"(\d{2})(\d{5} )(\d{5})(\d{1}) ");

          --
          Ludwig Stuyck

          Comment

          • Marcus Andrén

            #6
            Re: Splitting a String

            On Sat, 20 May 2006 13:37:27 +0200, Ludwig <none@none.co m> wrote:
            [color=blue]
            >Use regular expression (RegEx class) and its Split method!.[/color]

            While it is possible to use Regex.Split, it is definatly easier to
            read the substring version and the Regex is also more inefficent. Here
            is the regex version.

            public static string[] SplitBarCode(st ring barcode)
            {
            return Regex.Split(bar code,
            @"(?<= ^\d{2} | ^\d{7} | ^\d{12} )"
            ,RegexOptions.I gnorePatternWhi tespace)
            }

            --
            Marcus Andrén

            Comment

            • Marcus Andrén

              #7
              Re: Splitting a String

              On Sat, 20 May 2006 16:13:11 +0200, Ludwig <none@none.co m> wrote:
              [color=blue]
              >On Sat, 20 May 2006 13:19:28 +0100, "Mark Rae"
              ><mark@markN-O-S-P-A-M.co.uk> wrote:
              >[color=green]
              >>"Ludwig" <none@none.co m> wrote in message
              >>news:ppvt6214 9e2bb47ttv4qdkm i99uocrifpg@4ax .com...
              >>[color=darkred]
              >>> Use regular expression (RegEx class) and its Split method!.[/color]
              >>
              >>How could you use that in this case...?
              >>[/color]
              >
              >Out of my head:
              >string[] parts = Regex.Split("50 21378002392",
              >@"(\d{2})(\d{5 })(\d{5})(\d{1} )");[/color]

              That regex only works if you are using Regex.Match and iterates over
              the groups. That won't yield a one line solution though.

              Regex.Split uses the regex to detect boundries, so you would have to
              use lookbehind assertion to see how far from the beginning of the
              string you are. I posted the correct split regex in another post in
              this thread.

              --
              Marcus Andrén

              Comment

              • Ludwig

                #8
                Re: Splitting a String

                On Sat, 20 May 2006 19:19:35 +0200, Marcus Andrén <a@b.c> wrote:
                [color=blue]
                >On Sat, 20 May 2006 16:13:11 +0200, Ludwig <none@none.co m> wrote:
                >[color=green]
                >>On Sat, 20 May 2006 13:19:28 +0100, "Mark Rae"
                >><mark@markN-O-S-P-A-M.co.uk> wrote:
                >>[color=darkred]
                >>>"Ludwig" <none@none.co m> wrote in message
                >>>news:ppvt621 49e2bb47ttv4qdk mi99uocrifpg@4a x.com...
                >>>
                >>>> Use regular expression (RegEx class) and its Split method!.
                >>>
                >>>How could you use that in this case...?
                >>>[/color]
                >>
                >>Out of my head:
                >>string[] parts = Regex.Split("50 21378002392",
                >>@"(\d{2})(\d{ 5})(\d{5})(\d{1 })");[/color]
                >
                >That regex only works if you are using Regex.Match and iterates over
                >the groups. That won't yield a one line solution though.
                >
                >Regex.Split uses the regex to detect boundries, so you would have to
                >use lookbehind assertion to see how far from the beginning of the
                >string you are. I posted the correct split regex in another post in
                >this thread.[/color]

                Well I just tried it and it does work.... first and last element of
                the resulting array are empty though.
                --
                Ludwig Stuyck

                Comment

                • Marcus Andrén

                  #9
                  Re: Splitting a String

                  >Well I just tried it and it does work.... first and last element of[color=blue]
                  >the resulting array are empty though.[/color]

                  Heh, my bad. I even tested your code. I just forgot to actually print
                  out the values.

                  Anyway, I re-read the entry on Regex.Split. The reason there is an
                  extra first and last element when using your version with groups is
                  because of the following

                  MSDN Regex Split:
                  "
                  If capturing groups are used in a Regex.Split expression, the
                  capturing groups are included in the resulting string array. The
                  following example would yield the array items "one", "-", "two", "-",
                  "banana".

                  Regex r = new Regex("(-)"); // Split on hyphens.
                  string[] s = r.Split("one-two-banana");
                  "

                  Your regex treats the whole barcode as the delimiter and the first and
                  last element becomes the non existing data before and after the
                  barcode delimiter.

                  --
                  Marcus Andrén

                  Comment

                  • Ludwig

                    #10
                    Re: Splitting a String

                    On Sat, 20 May 2006 20:10:36 +0200, Marcus Andrén <a@b.c> wrote:
                    [color=blue][color=green]
                    >>Well I just tried it and it does work.... first and last element of
                    >>the resulting array are empty though.[/color]
                    >
                    >Heh, my bad. I even tested your code. I just forgot to actually print
                    >out the values.
                    >
                    >Anyway, I re-read the entry on Regex.Split. The reason there is an
                    >extra first and last element when using your version with groups is
                    >because of the following
                    >
                    >MSDN Regex Split:
                    >"
                    >If capturing groups are used in a Regex.Split expression, the
                    >capturing groups are included in the resulting string array. The
                    >following example would yield the array items "one", "-", "two", "-",
                    >"banana".
                    >
                    >Regex r = new Regex("(-)"); // Split on hyphens.
                    > string[] s = r.Split("one-two-banana");
                    >"
                    >
                    >Your regex treats the whole barcode as the delimiter and the first and
                    >last element becomes the non existing data before and after the
                    >barcode delimiter.[/color]

                    Right, thanks, I was wondering why that was :) But if you would have
                    to choose between using RegEx or using the SubString method, what
                    would you prefer and why?
                    --
                    Ludwig Stuyck

                    Comment

                    • Marcus Andrén

                      #11
                      Re: Splitting a String

                      >Right, thanks, I was wondering why that was :) But if you would have[color=blue]
                      >to choose between using RegEx or using the SubString method, what
                      >would you prefer and why?[/color]

                      In this case, either one is acceptable. I would probably still go with
                      Substring, because it is slightly easier to read and debug. I usually
                      save regular expressions for more complex pattern matching.

                      I do have one big pet issue when using regular expressions though. I
                      try to always use RegexOptions.Ig norePatternWhit espace so I can add
                      formatting and comments to make it more readable.

                      --
                      Marcus Andrén

                      Comment

                      • Mark Rae

                        #12
                        Re: Splitting a String

                        "Marcus Andrén" <a@b.c> wrote in message
                        news:19su629rk4 mco3pi4fioqo2p6 904lesb0q@4ax.c om...
                        [color=blue]
                        > In this case, either one is acceptable. I would probably still go with
                        > Substring, because it is slightly easier to read and debug. I usually
                        > save regular expressions for more complex pattern matching.[/color]

                        Agree 100%. I find that I almost never use RegEx for string splitting, but
                        almost always use it for validation.


                        Comment

                        • Rene Sørensen

                          #13
                          Re: Splitting a String

                          ludwigs exsample is good, another way to it is this.
                          the string is now spilt into groups, block1 is an eample of that


                          Regex RegexObj = new
                          Regex("\\A(?<bl ock1>\\d{2})(?< block2>\\d{5})( ?<block3>\\d{5} )(?<block4>\\d) ");
                          string block1 =RegexObj.Match (SubjectString) .Groups["block1"].Value;

                          block1 = 50;
                          block2 = 21378;
                          block3 = 00239;
                          block4 = 2;

                          On Sat, 20 May 2006 01:18:34 +0100, Materialised
                          <materialised@p rivacy.net> wrote:
                          [color=blue]
                          >Hi all,
                          >
                          >Just wondering if someone could help me with this little problem I'm having.
                          >
                          >I have a string value (it actually represents a barcode) which looks
                          >like this:
                          >
                          >502137800239 2
                          >
                          >What I wish to do is split this string in 4 different string values, as
                          >such:
                          >
                          >val1 = 50;
                          >val2 = 21378;
                          >val3 = 00239;
                          >val4 = 2;
                          >
                          >The placement of the values is actually fixed, so it will always be 2,5,5,1.
                          >Does anyone Know how i can do this?[/color]

                          Comment

                          • Jon Skeet [C# MVP]

                            #14
                            Re: Splitting a String

                            Rene Sørensen <reso@deltadk.d k> wrote:[color=blue]
                            > ludwigs exsample is good, another way to it is this.
                            > the string is now spilt into groups, block1 is an eample of that
                            >
                            >
                            > Regex RegexObj = new
                            > Regex("\\A(?<bl ock1>\\d{2})(?< block2>\\d{5})( ?<block3>\\d{5} )(?<block4>\\d) ");
                            > string block1 =RegexObj.Match (SubjectString) .Groups["block1"].Value;
                            >
                            > block1 = 50;
                            > block2 = 21378;
                            > block3 = 00239;
                            > block4 = 2; [/color]

                            And this is a good example of why you should really think about whether
                            regular expressions are the right solution before using them. Pretend
                            you don't know what the bit of code is meant to do, and read the
                            version above. Then read Nick's version using String.Substrin g. I know
                            which I find significantly simpler to understand...

                            --
                            Jon Skeet - <skeet@pobox.co m>
                            http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
                            If replying to the group, please do not mail me too

                            Comment

                            • Ludwig

                              #15
                              Re: Splitting a String

                              On Sun, 21 May 2006 15:19:07 +0100, Jon Skeet [C# MVP]
                              <skeet@pobox.co m> wrote:
                              [color=blue]
                              >Rene Sørensen <reso@deltadk.d k> wrote:[color=green]
                              >> ludwigs exsample is good, another way to it is this.
                              >> the string is now spilt into groups, block1 is an eample of that
                              >>
                              >>
                              >> Regex RegexObj = new
                              >> Regex("\\A(?<bl ock1>\\d{2})(?< block2>\\d{5})( ?<block3>\\d{5} )(?<block4>\\d) ");
                              >> string block1 =RegexObj.Match (SubjectString) .Groups["block1"].Value;
                              >>
                              >> block1 = 50;
                              >> block2 = 21378;
                              >> block3 = 00239;
                              >> block4 = 2;[/color]
                              >
                              >And this is a good example of why you should really think about whether
                              >regular expressions are the right solution before using them. Pretend
                              >you don't know what the bit of code is meant to do, and read the
                              >version above. Then read Nick's version using String.Substrin g. I know
                              >which I find significantly simpler to understand...[/color]

                              I agree! The format is well-known, so RegEx is not the best and most
                              simple solution. Of course, if you are a regular expressions expert,
                              this piece of code may be just as simple as using SubString...
                              --
                              Ludwig Stuyck

                              Comment

                              Working...