我有这些号码00012001,0000012002,012003,12004等。如果这些号码中的一个是随机选择的,我想在号码前找到零并以字符串形式存储。
例如,
如果选择00012001,' 000'存储在String变量中。
如果选择0000012002,那么' 00000'存储在String中。数字前面可能有也可能没有零。
有没有办法在这些数字前面找到零?感谢。
答案 0 :(得分:3)
使用LINQ很容易:
Dim zeros = selected.ToString().TakeWhile(Function(c) c = "0"c)
Dim zeroString = New String(zeros.ToArray())
我想到的另一种方法是:
dim countZeros = selected.Length - selected.TrimStart("0"c).Length
zeroString = New string("0"c, countZeros)
Trevor说这是一个很好的扩展候选者,这是一个优化版本:
Public Module StringExtensions
<System.Runtime.CompilerServices.Extension> _
Public Function TrimStartGetTrimmed(str As String, ParamArray charsToTrim As Char()) As String
If str Is Nothing Then
Throw New ArgumentNullException(NameOf(str))
End If
Dim whiteSpaceCheck As Boolean = charsToTrim Is Nothing OrElse charsToTrim.Length = 0
Dim firstNonTrimCharIndex As Integer = 0
For Each current As Char In str
Dim isTrimChar As Boolean = If(whiteSpaceCheck, Char.IsWhiteSpace(current), charsToTrim.Contains(current))
If Not isTrimChar Then
Return str.Substring(0, firstNonTrimCharIndex)
End If
firstNonTrimCharIndex += 1
Next
Return str
End Function
<System.Runtime.CompilerServices.Extension> _
Public Function TrimEndGetTrimmed(str As String, ParamArray charsToTrim As Char()) As String
If str Is Nothing Then
Throw New ArgumentNullException(NameOf(str))
End If
Dim whiteSpaceCheck As Boolean = charsToTrim Is Nothing OrElse charsToTrim.Length = 0
For index = str.Length - 1 To 0 Step -1
Dim current As Char = str(index)
Dim isTrimChar As Boolean = If(whiteSpaceCheck, Char.IsWhiteSpace(current), charsToTrim.Contains(current))
If Not isTrimChar Then
Return str.Substring(index + 1)
End If
Next
Return str
End Function
End Module
这对C#来说是相同的:
public static class StringExtensions
{
public static string TrimStartGetTrimmed(this string str, params char[] charsToTrim)
{
if (str == null) throw new ArgumentNullException(nameof(str));
bool whiteSpaceCheck = charsToTrim == null || charsToTrim.Length == 0;
for (var index = 0; index < str.Length; index++)
{
char current = str[index];
bool isTrimChar = whiteSpaceCheck ? char.IsWhiteSpace(current) : charsToTrim.Contains(current);
if (!isTrimChar)
return str.Substring(0, index);
}
return str;
}
public static string TrimEndGetTrimmed(this string str, params char[] charsToTrim)
{
if (str == null) throw new ArgumentNullException(nameof(str));
bool whiteSpaceCheck = charsToTrim == null || charsToTrim.Length == 0;
for (var index = str.Length - 1; index >= 0; index--)
{
char current = str[index];
bool isTrimChar = whiteSpaceCheck ? char.IsWhiteSpace(current) : charsToTrim.Contains(current);
if (!isTrimChar)
return str.Substring(index + 1);
}
return str;
}
}
答案 1 :(得分:0)
这也应该有效:
Function zerodigits(ByVal str As String)
Dim re As String = ""
For Each c As Char In str
Select Case c
Case "0"c : re &= c
Case Else : Return re
End Select
Next
Return re
End Function