分开的数字范围,如果按顺序连字符,则按连字符;如果发生顺序连字符,则逗号 [英] Separate range of numbers, if in sequence then by hyphen, and if break in sequence occurs then comma character

查看:129
本文介绍了分开的数字范围,如果按顺序连字符,则按连字符;如果发生顺序连字符,则逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a string denoting page nos like 1,2,3,4,8,9,10,15.

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

I want this to be shown as 1-4,8-10,15 i.e numbers in sequence are separated by hyphen enclosed by smallest and largest number in sequence.

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

If break in sequence, the range is to be separated by comma.

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);


推荐答案

我认为循环内循环正在使事情产生更令人困惑。尝试仅使用一个循环,因为您只需要遍历整个列表一次。

I think the loop-within-loop is making things more confusing. Try using just a single loop, because you only need to iterate over the entire list once.

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

这篇关于分开的数字范围,如果按顺序连字符,则按连字符;如果发生顺序连字符,则逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆