|
-
Jul 13th, 2011, 09:53 AM
#1
Thread Starter
PowerPoster
[RESOLVED] Shorten code
Ola,
I want a textbox to be checked for specific characters. I can use:
Code:
with textbox1.text
If .contains("a") or .contains("b") or .contains("c")...etc... then...
How can I shorten this?
-
Jul 13th, 2011, 10:17 AM
#2
Re: Shorten code
Code:
If text.IndexOfAny(New Char() {"a"c, "b"c, "c"c}) > -1 Then
-
Jul 13th, 2011, 10:18 AM
#3
Re: Shorten code
You can use the String.IndexOf (Any) to give you the loction of any of those characters and bail. Example here.
-
Jul 13th, 2011, 11:09 AM
#4
Thread Starter
PowerPoster
Re: Shorten code
Thank you both. Will have a look at it.
-
Jul 13th, 2011, 03:45 PM
#5
Thread Starter
PowerPoster
Re: Shorten code
Had to figure out why it kept saying that there was an illegal character although it wasn't.
"If text.IndexOfAny(New Char() {"a"c, "b"c, "c"c}) > -1 Then" means something like: When not one of the characters found in the index of the text".
If someone knows how to formulate it better, please let me know.
+REP btw.
-
Jul 13th, 2011, 03:51 PM
#6
Re: Shorten code
I can only guess that you want to run the If when you DO NOT have a value that matches, so just change it.
IndexOfAny.... = -1
-
Jul 13th, 2011, 03:52 PM
#7
Thread Starter
PowerPoster
Re: Shorten code
I figured that already m8. "issue" was solved already. Thanks again.
-
Jul 13th, 2011, 04:06 PM
#8
Re: [RESOLVED] Shorten code
These are just some examples:
Code:
Dim text = "the quick brown fox!"
Dim letters = "abc".ToCharArray()
If Not text.ContainsAny("a"c, "b"c, "c"c) Then
End If
'//or
If Not text.ContainsAny(letters) Then
End If
'//or
If Not text.IndexOfAny(letters) > -1 Then
End If
Public Module StringExtensions
''' <summary>
''' Returns a value indicating whether any of the specified <see cref="System.Char" />
''' objects occur within this string.
''' </summary>
''' <param name="value">The value whose characters to check.</param>
''' <param name="chars">The <see cref="System.Char" /> objects to seek.</param>
<Runtime.CompilerServices.Extension()> _
Public Function ContainsAny(ByVal value As String, _
ByVal ParamArray chars() As Char) As Boolean
Return value.IndexOfAny(chars) > -1
End Function
End Module
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|