单独的数字范围,如果按顺序由连字符,如果顺序发生中断,那么逗号

编程入门 行业动态 更新时间:2024-10-24 04:31:47
本文介绍了单独的数字范围,如果按顺序由连字符,如果顺序发生中断,那么逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个字符串表示页号如 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;

演示: ideone/7HdpS7

更多推荐

单独的数字范围,如果按顺序由连字符,如果顺序发生中断,那么逗号

本文发布于:2023-11-29 13:40:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646537.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:顺序   逗号   字符   发生   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!