我只想從字符串中獲取數字。只獲取字符串中的數字
免得說,這是我的字符串:
324ghgj123
我想:
324123
我曾嘗試:
MsgBox(Integer.Parse("324ghgj123"))
我只想從字符串中獲取數字。只獲取字符串中的數字
免得說,這是我的字符串:
324ghgj123
我想:
324123
我曾嘗試:
MsgBox(Integer.Parse("324ghgj123"))
試試這個:
Dim mytext As String = "123a123"
Dim myChars() As Char = mytext.ToCharArray()
For Each ch As Char In myChars
If Char.IsDigit(ch) Then
MessageBox.Show(ch)
End If
Next
或:
Private Shared Function Num(ByVal value As String) As Integer
Dim returnVal As String = String.Empty
Dim collection As MatchCollection = Regex.Matches(value, "\d+")
For Each m As Match In collection
returnVal += m.ToString()
Next
Return Convert.ToInt32(returnVal)
End Function
或者你可以使用一個事實,即一個String是一個字符數組。
Public Function getNumeric(value As String) As String
Dim output As StringBuilder = New StringBuilder
For i = 0 To value.Length - 1
If IsNumeric(value(i)) Then
output.Append(value(i))
End If
Next
Return output.ToString()
End Function
resultString = Regex.Match(subjectString, @"\d+").Value;
會給你這個數字作爲一個字符串。然後Int32.Parse(resultString)會給你這個數字。
這是C#,而不是VB.NET,否則,最短的,謝謝! – monami
對於線性搜索方法,您可以使用這種算法,它使用C#,但可以很容易地在vb.net中翻譯,希望它有幫助。
string str = 「123a123」;
for(int i=0;i<str.length()-1;i++)
{
if(int.TryParse(str[i], out nval))
continue;
else
str=str.Rremove(i,i+1);
}
實際上,你可以結合一些個別的答案創建一個單一的線解決方案,要麼值爲0,或者一個整數的所有字符串中的數字的級聯返回一個整數。然而,不知道這是多麼有用 - 這開始作爲創建一串數字的方法...
Dim TestMe = CInt(Val(New Text.StringBuilder((From ch In "123abc123".ToCharArray Where IsNumeric(ch)).ToArray).ToString))
謝謝。作品。 – Nh123
沒問題。 :-) – famf