缩短号码列表与连续的数字之间的连字符。 [英] Shortening list of numbers with hyphens between consecutive numbers

查看:155
本文介绍了缩短号码列表与连续的数字之间的连字符。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个简单的方法,采取可以是范围为1号的列表 - 15。而且把一个破折号的地方连续编号。

这样,例如,如果你有以下号码:

1 2 3 5 6 7 10 12

这将输出

1 - 3,5 - 7,10,12

解决方案

 < PHP
的$ n =阵列(1,2,3,5,6,7,10,12);
排序($ N); //如果有必要的。
$ i = 0;
而($ I<计数($ N))
  {
    如果($ I!= 0)
      打印 (, );
    $的RangeStart = $ I;
    打印($ N [$ i ++]);
    而($ I<计数($ N)及和放大器; $ N [$ i] == $ N [$ I  -  1] + 1)
      $ I ++;
    如果($ I> $的RangeStart + 1)
      打印( - $ N [$ I  -  1]);
  }
 

Is there a simple way to take a list of numbers which can be in the range 1 - 15. And put a dash in place of consecutive numbers.

So that for example if you had the following numbers:

1 2 3 5 6 7 10 12

It would output

1 - 3, 5 - 7, 10, 12

解决方案

<?php
$n = array (1, 2, 3, 5, 6, 7, 10, 12);
sort ($n);   // If necessary.
$i = 0;
while ($i < count ($n))
  {
    if ($i != 0)
      print (", ");
    $rangestart = $i;
    print ($n [$i++]);
    while ($i < count ($n) && $n [$i] == $n [$i - 1] + 1)
      $i++;
    if ($i > $rangestart + 1)
      print (" - " . $n [$i - 1]);
  }

这篇关于缩短号码列表与连续的数字之间的连字符。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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