[2008] How to check if all the chars in a string are different from each other?
Hi!!
How can I check if all the chars in a string are different from each other? In other words how can I check if there are repeated chars in a string?
Thks a lot!
Re: [2008] How to check if all the chars in a string are different from each other?
try this:
vb Code:
MsgBox("string contains duplicate characters = " & checkString("astringa"))
vb Code:
Private Function checkString(ByVal str As String) As Boolean
For x As Integer = 0 To str.Length - 1
If x > 0 Then
If CStr(str.Substring(0, x) & str.Substring(x + 1, str.Length - (x + 1))).Contains(str.Substring(x, 1)) Then
Return True
End If
Else
If str.Substring(x + 1, str.Length - (x + 1)).Contains(str.Substring(x, 1)) Then
Return True
End If
End If
Next
Return False
End Function
Re: [2008] How to check if all the chars in a string are different from each other?
Well, the question is a little bit vague. You don’t specify the casing. If the method should be case sensitive, than here is the method:
Code:
'Case sensitive
Private Function ContainsDuplicate(ByRef str As String) As Boolean
For i As Integer = 0 To str.Length - 1
If str.Substring(0, i).Contains(str.Substring(i, 1)) Then
Return True
End If
Next
Return False
End Function
If it is not spouse to be case sensitive, than add ToLower method after str and leave the rest the same, here is an example:
Code:
'None case sensitive
Private Function ContainsDuplicate(ByRef str As String) As Boolean
For i As Integer = 0 To str.Length - 1
If str.ToLower.Substring(0, i).Contains(str.ToLower.Substring(i, 1)) Then
Return True
End If
Next
Return False
End Function
Re: [2008] How to check if all the chars in a string are different from each other?
vb.net Code:
For index As Integer = 0 To myString.Length - 1
If myString.LastIndexOf(myString(index)) <> index Then
'There is a least one more occurrence in the string of the character at the current index.
End If
Next