小编典典

分开的数字范围,如果按顺序连字符,则按连字符;如果发生顺序连字符,则逗号

algorithm

我有一个字符串,表示类似的页面编号1,2,3,4,8,9,10,15

我希望将其显示为,1-4,8-10,15 即序列中的数字用连字符分隔,连字符用序列中的最小和最大数字包围。

如果顺序中断,则范围用逗号分隔。

string pageNos = "5,6,7,9,10,11,12,15,16";
string result=string.Empty;
string[] arr1 = pageNos.Split(',');
int[] arr = new int[arr1.Length];

for (int x = 0; x < arr1.Length; x++) // Convert string array to integer array
{
    arr[x] = Convert.ToInt32(arr1[x].ToString());
}

for (int i = 0; i < arr.Length;i++)
{
    for (int j = i + 1; ; j++)
        if (arr[i] == (arr[j] - 1))
            result += arr[i].ToString() + "-" + arr[j].ToString();
        else
            result += arr[i].ToString() + ",";
}

Console.WriteLine(result);

阅读 283

收藏
2020-07-28

共1个答案

小编典典

我认为循环内循环使事情变得更加混乱。尝试仅使用一个循环,因为您只需要遍历整个列表一次。

int start,end;  // track start and end
end = start = arr[0];
for (int i = 1; i < arr.Length; i++)
{
    // as long as entries are consecutive, move end forward
    if (arr[i] == (arr[i - 1] + 1))
    {
        end = arr[i];
    }
    else
    {
        // when no longer consecutive, add group to result
        // depending on whether start=end (single item) or not
        if (start == end)
            result += start + ",";
        else if (end == (start + 1))
            result += start + "," + end + ",";
        else
            result += start + "-" + end + ",";

        start = end = arr[i];
    }
}

// handle the final group
if (start == end)
    result += start;
else
    result += start + "-" + end;

演示:http//ideone.com/7HdpS7

2020-07-28