1
string num = db.SelectNums(id);
string[] numArr = num.Split('-').ToArray();

string num contain for an example "48030-48039";

string[] numArr will therefor contain (48030, 48039).

Now I have two elements, a high and low. I now need to get ALL the numbers from 48030 to 48039. The issue is that it has to be string since there will be telephone numbers with leading zeroes now and then.

Thats why I cannot use Enumerable.Range().ToArray() for this.

Any suggestions? The expected result should be 48030, 48031, 48032, ... , 48039

10
  • So, basically, you're asking how to convert integers into strings, and then join them into a single string?
    – vgru
    May 22, 2014 at 10:43
  • What number between 48030 and 48039 has a leading zero?.. Regardless, it doesn't have to be a string as you can just Pad the string with zeros by the sound of it after you have the range
    – Sayse
    May 22, 2014 at 10:44
  • @Sayse if you'd use some sort of padding for a fixed length ... but very strange indeed :)
    – user57508
    May 22, 2014 at 10:45
  • @Sayse I said there will be numbers with leading zeroes now and then. Basically I want an array with each number in the range as a seperate element. May 22, 2014 at 10:47
  • 1
    What means telephone numbers with leading zeroes now and then? What is the problem with leading zeros? Why don't you show what you want as result or an example of the number with leading zero which you can't parse? May 22, 2014 at 10:51

8 Answers 8

1

This should work with your leading zero requirement:

string num = db.SelectNums(id);
string[] split = num.Split('-');

long start = long.Parse(split[0]);
long end = long.Parse(split[1]);
bool includeLeadingZero = split[0].StartsWith("0");

List<string> results = new List<string>();

for(int i = start; i <= end; i++)
{
    string result = includeLeadingZero ? "0" : "";
    result += i.ToString();
    results.Add(result);
}

string[] arrayResults = results.ToArray();

A few things to note:

  • It assumes your input will be 2 valid integers split by a single hyphen
  • I am giving you a string array result, personally I would prefer to work with a List<int> in the end
  • If the first number contains a single leading zero, then all results will contain a single leading zero
  • It uses long to cater for longer numbers, beware that the max number that will parse is 9,223,372,036,854,775,807, you could double this value (not length) by using ulong
9
  • I tried this and "I get Value was either too large or too small for an Int32." split[0] contains "4618155500". Remember that the 48030 is just an example. The numbers will vary a lot. May 22, 2014 at 10:49
  • @user3218338: How many leading zeroes do you want then? Your example only had 5 digits. EDIT: Then in this case, you may want to consider using long, but now I'm wondering if the ranges are too large in this case to be useable; we may want to employ deferred execution here. May 22, 2014 at 10:50
  • The number can vary from XXXX to XXXXXXXXXXXXX. There will only be one leading zero at most. EDIT: Why would it be so hard to get the range from 4553030 - 4553039. It is 10 numbers? May 22, 2014 at 10:51
  • @user3218338: Sorry, missed the leading zero requirement... but how will you determine if one of the generated numbers should have a leading zero?
    – musefan
    May 22, 2014 at 10:52
  • I'd like to treat them as a string, therefor I do not have to worry about the leading zero. May 22, 2014 at 10:52
0

Are you saying this?

int[] nums = new int[numArr.Length];
for (int i = 0; i < numArr.Length; i++)
{
    nums[i] = Convert.ToInt32(numArr[i]);
}
Array.Sort(nums);
for (int n = nums[0]; n <= nums[nums.Length - 1]; n++)
{
    Console.WriteLine(n);
}

here link

0

I am expecting your string always have valid two integers, so using Parse instead TryParse

string[] strList = "48030-48039".Split('-').ToArray();

var lst = strList.Select(int.Parse).ToList();
var min = lst.OrderBy(l => l).FirstOrDefault();
var max = lst.OrderByDescending(l => l).FirstOrDefault();
var diff = max - min;

//adding 1 here otherwise 48039 will not be there
var rng = Enumerable.Range(min,diff+1);

If you expecting invalid string

 var num = 0;
 var lst = (from s in strList where int.TryParse(s, out num) select num).ToList();
0

This is one way to do it:

    public static string[] RangeTest()
    {
        Boolean leadingZero = false;
        string num = "048030-48039"; //db.SelectNums(id);
        if (num.StartsWith("0"))
            leadingZero = true;

        int min = int.Parse(num.Split('-').Min());
        int count = int.Parse(num.Split('-').Max()) - min;
        if (leadingZero)
            return Enumerable.Range(min, count).Select(x => "0" + x.ToString()).ToArray();
        else
            return Enumerable.Range(min, count).Select(x => "" + x.ToString()).ToArray(); ;
    }
0

You can use string.Format to ensure numbers are formatted with leading zeros. That will make the method work with arbitrary number of leading zeros.

private static string CreateRange(string num)
{
    var tokens = num.Split('-').Select(s => s.Trim()).ToArray();

    // use UInt64 to allow huge numbers
    var start = UInt64.Parse(tokens[0]);
    var end = UInt64.Parse(tokens[1]);

    // if your start number is '000123', this will create
    // a format string with 6 zeros ('000000')
    var format = new string('0', tokens[0].Length);

    // use StringBuilder to make GC happy.
    // (if only there was a Enumerable.Range<ulong> overload...)
    var sb = new StringBuilder();
    for (var i = start; i <= end; i++)
    {
        // format ensures that your numbers are padded properly
        sb.Append(i.ToString(format));
        sb.Append(", ");
    }

    // trim trailing comma after the last element
    if (sb.Length >= 2) sb.Length -= 2;

    return sb.ToString();
}

Usage example:

// prints 0000012, 0000013, 0000014
Console.WriteLine( CreateRange("0000012-0000014") );
0

Three significant issues were brought up in comments:

  1. The phone numbers have enough digits to exceed Int32.MaxValue so converting to int isn't viable.

  2. The phone numbers can have leading zeros (presumeably for some international calling?)

  3. The possible range of numbers can theoretically exceed the maximum size of an array (which may have memory issues, and I think may not be represented as a string)

As such, you may need to use long instead of int, and I would suggest using deferred execution if needed for very large ranges.

public static IEnumerable<string> EnumeratePhoneNumbers(string fromAndTo)
{
    var split = fromAndTo.Split('-');

    return EnumeratePhoneNumbers(split[0], split[1]);
}

public static IEnumerable<string> EnumeratePhoneNumbers(string fromString, string toString)
{
    long from = long.Parse(fromString);
    long to = long.Parse(toString);

    int totalNumberLength = fromString.Length;

    for (long phoneNumber = from; phoneNumber <= to; phoneNumber++)
    {
        yield return phoneNumber.ToString().PadLeft(totalNumberLength, '0');
    }
}

This assumes that the padded zeros are already included in the lower bound fromString text. It will iterate and yield out numbers as you need them. This can be useful if you're churning out a lot of numbers and don't need to fill up memory with them, or if you just need the first 10 or 100. For example:

var first100Numbers = 
    EnumeratePhoneNumbers("0018155500-7018155510")
    .Take(100)
    .ToArray();

Normally that range would produce 7 billion results which cannot be stored in an array, and might run into memory issues (I'm not even sure if it can be stored in a string); by using deferred execution, you only create the 100 needed.

If you do have a small range, you can still join up your results into a string as you desired:

string numberRanges = String.Join(", ", EnumeratePhoneNumbers("0018155500-0018155510"));

And naturally you can put this array creation into your own helper method:

public static string GetPhoneNumbersListing(string fromAndTo)
{
    return String.Join(", ", EnumeratePhoneNumbers("0018155500-0018155510"));
}

So your usage would be:

string numberRanges = GetPhoneNumbersListing("0018155500-0018155510");
0

A complete solution inspired by the answer by @Dan-o:

Inputs:

Start:  48030
End:    48039
Digits:     6

Expected String Output:

048030, 048031, 048032, 048033, 048034, 048035, 048036, 048037, 048038, 048039

Program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class Program
{
    public static void Main()
    {
        int first  = 48030;
        int last   = 48039;
        int digits = 6;

        Console.WriteLine(CreateRange(first, last, digits));
    }

    public static string CreateRange(int first, int last, int numDigits)
    {
        string separator = ", ";

        var sb = new StringBuilder();
        sb.Append(first.ToString().PadLeft(numDigits, '0'));

        foreach (int num in Enumerable.Range(first + 1, last - first))
        {
            sb.Append(separator + num.ToString().PadLeft(numDigits, '0'));
        }

        return sb.ToString();
    }
}
-1
For Each item In Enumerable.Range(min, count).ToArray()
  something = item.PadLeft(5, "0")
Next
2
  • 1
    Exactly what I was thinking, but this is not c#
    – Sayse
    May 22, 2014 at 10:47
  • @Sayse: that is correct. Gold star for your observation skills. Kidding aside, translation to C# is incredibly trivial. I'm sure the OP is capable.
    – Sam Axe
    May 22, 2014 at 10:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.