我只想从字符串中获取数字。只获取字符串中的数字
免得说,这是我的字符串:
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