Java把数组里面能连起来的数字连起来方法

| 阅读数:--次| 作者:小豆豆
摘要:Java把数组里面能连起来的数字连起来方法
java代码
/**
	 * 把数组数字连号显示
	 * 
	 * @param zfsArr   String zfsArr[] = { "1", "5", "2","6","8","10","12" };
	 * @return   1-2,5-6,8,10,12
	 */
	public static String lh(String[] zfsArr) {
		StringBuffer strQzhm = new StringBuffer();
		if (zfsArr != null && zfsArr.length > 0) {
			if (zfsArr.length == 1) {
				return zfsArr[0].trim();
			}
			long zfs[] = new long[zfsArr.length];
			for (int i = 0; i < zfsArr.length; i++) {
				zfs[i] = Long.parseLong(zfsArr[i].trim());
			}
			Arrays.sort(zfs);
			int tempInt = 0;

			for (int i = 1; i < zfs.length; i++) {
				if (zfs[i] - zfs[i - 1] == 1) {
					tempInt++;
					if (i == zfs.length - 1) {
						strQzhm.append(zfs[i - tempInt] + "-" + zfs[i] + ",");
					}
				} else {
					if (tempInt == 0) {
						strQzhm.append(zfs[i - tempInt - 1] + ",");
					} else {
						strQzhm.append(zfs[i - tempInt - 1] + "-" + zfs[i - 1]
								+ ",");
					}
					tempInt = 0;
				}
			}
			if (strQzhm.indexOf(String.valueOf(zfs[zfs.length - 1])) == -1) {
				strQzhm.append(zfs[zfs.length - 1]);
			}
		}
		return strQzhm.toString();
	}
返回顶部
学到老代码浏览 关闭浏览