大佬教程收集整理的这篇文章主要介绍了如何在数组中存储由逗号和连字符分隔的数字范围?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我必须以特殊方式将字符串中包含的数字存储到数组中。
该字符串包含逗号和连字符。
例如,我的字符串是:
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
需要考虑的一些步骤:
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,请注明来意。