0

How do I modify the index number from an array to have a preceding 0 for number 1 - 9. However, I would like numbers 10 on up to remain the same.

This is the raw data from debugging when getting my data from the tb1.text

"1ABC\r\n2ABC\r\3ABC\r\4ABC\r\n5ABC" 

This is how I would like to store the data in my localDB.

"01ABC\r\n02ABC\r\03ABC\r\04ABC\r\n...10ABC"

Here is what I have so far.

var lines = tb1.Text.Split('\n').Select((line, index) => "YRZ"+(index + 01) + line).ToArray();

var res = string.Join("\n", lines);
J. Ballard
  • 33
  • 2
  • 9
  • possible duplicate of [Number formatting: how to convert 1 to "01", 2 to "02", etc.?](http://stackoverflow.com/questions/5972949/number-formatting-how-to-convert-1-to-01-2-to-02-etc) – Vsevolod Goloviznin Dec 04 '14 at 17:26
  • Thanks for the insight Vsevolod Goloviznin. I seems to have one slight issue now. When I implement the number formatting the 1st number is now 00 and not 01. – J. Ballard Dec 04 '14 at 18:22
  • 1
    That's because indexes in c# are starting from 0. Try adding a '1' to your index and then calling ToString. (index + 1).ToString("D2") – Vsevolod Goloviznin Dec 04 '14 at 18:25

2 Answers2

1

Since the indexes are already part of the data entered, you need to either read it from there (and use that index) or remove it from there (and use the index you can get while Selecting). You can parse it using a regular expression. Once you have the index isolated, you can use .ToString("00") to add a leading zero.

var regex = new Regex(@"^(\d+)(.*)$");
var result = string.Join("\r\n",
    tb1.Text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(x =>
    {
        var m = regex.Match(x);
        return int.Parse(m.Groups[1].Value).ToString("00") + m.Groups[2].Value;
    }));
Debug.Assert("01ABC\r\n02ABC\r\n03ABC\r\n04ABC\r\n10ABC" == result);
Tim S.
  • 55,448
  • 7
  • 96
  • 122
-1

If you only want 0 in the string why not updating it as a string:

var text = "1ABC\r\n2ABC\r\n3ABC\r\n4ABC\r\n5ABC";
var lines = text.Split('\n').ToList();
var withZero = lines.Select(
            (line, i) =>
                {
                    var newVal = i < 9 ? string.Format("0{0}", line) : line;
                    return newVal;
                });
var result = string.Join("\n", withZero);

Or in a more concise form:

var result = string.Join("\n", text.Split('\n').Select(
            (line, i) =>
                {
                    var newVal = i < 9 ? string.Format("0{0}", line) : line;
                    return newVal;
                }));
PiotrWolkowski
  • 8,408
  • 6
  • 48
  • 68