-6

I want to input a series of Hex numbers into a textBox and when the user hits a button separate each byte with a comma. AAFFBCEE becomes AA,FF,BC,EE (no comma on last byte). how can I convert a string value to this format?

john
  • 159
  • 3
  • 16
  • Please use google and search for mac address and hex format. SO is full of questions and of cause also answers to hex formatting. – Paebbels Dec 19 '14 at 15:50
  • To split the string to chunks of fixed size see [this](http://stackoverflow.com/questions/1450774/splitting-a-string-into-chunks-of-a-certain-size). To add commas and produce new string use this `String.Join(",", stringChunks.ToArray())`. – Dialecticus Dec 19 '14 at 15:51

2 Answers2

1
    string temp = "aaff4455";
    string temp2 = "";
    int size = temp.Length;

    for (int i = 0; i < size; i += 2)
    {
        temp2 += temp.Substring(i, 2);
        if ((i+2) < size)
            temp2 += ",";
    }
LPs
  • 16,045
  • 8
  • 30
  • 61
  • It is generally bad form to use string concatenation in a loop. As long as the input string is very short, this may be okay. But otherwise, you should be using the [`StringBuilder.Append(string, int, int)`](http://msdn.microsoft.com/en-us/library/kc12ydtf(v=vs.110).aspx) overload instead. – Peter Duniho Dec 19 '14 at 15:58
  • We are talking about a TextBox not a stream... Thank you for -1 – LPs Dec 19 '14 at 15:59
  • You're welcome. A `TextBox` can easily contain enough text for it to be a problem to use the wrong implementation here. In any case, it's no harder to do it correctly than to do it wrong, so why add a bad example of how to build a string when you could provide a good example instead? Write a _good_ answer if you don't want a down-vote. It's easy enough; I've already told you how. All you have to do is edit the answer you gave. – Peter Duniho Dec 19 '14 at 16:04
  • Sorry teacher... Good answer depends on what you think, man. I think that in this case is better a faster code then "erudite" one that is time waster – LPs Dec 19 '14 at 16:08
  • why is this solution bad form? there could potentially be a lot of data in the textbox, sorry I'm knew to programming, trying to teach myself – john Dec 19 '14 at 16:25
1

Why not use a 1-liner?

var str = "AABBCCDD";
var result = "";

str.ToCharArray()
      .Select((c, i) => new { i, c })
      .ToList()
      .ForEach(c => result += (c.i > 0 && c.i % 2 == 0) ? "," + c.c : c.c.ToString());

(I'm still learning Linq so be nice!)

ne1410s
  • 6,864
  • 6
  • 55
  • 61