程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何在数组中存储由逗号和连字符分隔的数字范围?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决如何在数组中存储由逗号和连字符分隔的数字范围??

开发过程中遇到如何在数组中存储由逗号和连字符分隔的数字范围?的问题如何解决?下面主要结合日常开发的经验,给出你关于如何在数组中存储由逗号和连字符分隔的数字范围?的解决方法建议,希望对你解决如何在数组中存储由逗号和连字符分隔的数字范围?有所启发或帮助;

我必须以特殊方式将字符串中包含的数字存储到数组中。
该字符串包含逗号和连字符。

  • 逗号分隔的数字应单独存储
  • 由连字符分隔的数字应存储为值范围。

例如,我的字符串是:

Reg. No 556002,556010-556013,556039 Cancelled 

数组应将数字存储为:

(0) 556002   - Single
(1) 556010   ---------|
(2) 556011    Range of
(3) 556012    values
(4) 556013   ---------|
(5) 556039   - Single

我尝试了以下代码:

Dim i,str
Dim array() As Char = str.tochararray()
Dim rnoarray() As Integer = New Integer() {}
Dim rno = ""
Dim nosta As Boolean
Dim j = 0
str = "Reg. No 556002,556039 Cancelled"
nosta = false
ReDim rnoarray(Len(str) + 2)
For i = 0 To Len(str)-1
If IsNumeric(array(i)) Then
rno = rno & array(i)
nosta = True
Else
If nosta = True Then
rnoarray(j) = Val(rno)
j = j + 1
nosta = false
rno = ""
End If
End If
Next
For x = 0 To j - 1
messageBox.Show(rnoarray(X))
Next

但结果只包含四个数字:

556002
556010
556013
556039

解决方法

需要虑的一些步骤:

  • 从输入字符串中提取数字,保留出现的连字符
  • 验证其中一个部分是否包含连字符:
    • 在本例中,Split() 将字符串分成两部分
    • 转换为Integer两部分
    • 取最小值和最大值
    • 创建一个介于最小值和最大值之间的数字范围
    • 将数字范围添加到 List(Of Integer)
  • 将不包含连字符的字符串转换为 Integer
  • 将转换后的数字添加到 List(Of Integer)
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text.RegularExpressions

Dim input = "Reg. No 556002,556010-556013,556039 Cancelled"
Dim numbers As New List(Of Integer)

Dim matches = Regex.Matches(input,"\d+-*\d*").ofType(Of Match)
For Each m As Match In matches
    If m.Value.Contains("-") Then
        Dim parts = m.Value.Split("-"C).SELEct(Function(s) Integer.Parse(s)).ToArray()
        Dim nStart As Integer = Math.Min(parts(0),parts(1))
        Dim nEnd As Integer = Math.Max(parts(0),parts(1))
        numbers.AddRange(Enumerable.Range(nStart,nEnd - nStart + 1))
    Else
        numbers.Add(Integer.Parse(m.value))
    End If
Next

没有正则表达式(假设这里显示的输入字符串格式与原始格式匹配):

For Each part As String In input.Split(","C)
    If part.Contains("-") Then
        Dim nValues = part.Split("-"C).SELEct(Function(s) Integer.Parse(s)).ToArray()
        Dim nStart As Integer = Math.Min(nValues(0),nValues(1))
        Dim nEnd As Integer = Math.Max(nValues(0),nValues(1))
        numbers.AddRange(Enumerable.Range(nStart,nEnd - nStart + 1))
    Else
        Dim sValue = String.Concat(part.Where(Function(C) Char.IsDigit(C)))
        numbers.Add(Integer.Parse(svalue))
    End If
Next

大佬总结

以上是大佬教程为你收集整理的如何在数组中存储由逗号和连字符分隔的数字范围?全部内容,希望文章能够帮你解决如何在数组中存储由逗号和连字符分隔的数字范围?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: