单独的数字范围,如果按顺序由连字符,如果顺序发生中断,那么逗号 [英] Seperate range of numbers if in sequence by hyphen and if break in sequence occurs, then comma character
本文介绍了单独的数字范围,如果按顺序由连字符,如果顺序发生中断,那么逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串表示页号如 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 seperated by hyphen enclosed by smallest and largest number in sequence.
如果按顺序突破,范围由逗号分隔。
If break in sequence , the range is to be seperated 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
result += start + "-" + end + ",";
start = end = arr[i];
}
}
// handle the final group
if (start == end)
result += start;
else
result += start + "-" + end;
这篇关于单独的数字范围,如果按顺序由连字符,如果顺序发生中断,那么逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文