0

I am trying to find whether the character is present in a given string or not but unable to search and increment value though it is present

  Dim testchar,noOfSpecialChar
   noOfSpecialChar=0

Dim specialChars
specialChars="*[@.^$|?#*+!)(_=-]."
 for lngIndex = 1 to Len("test@123")
    testchar = mid("test@123",lngIndex,1)
    if((InStr(specialChars,testchar))) then
        noOfSpecialChar=noOfSpecialChar+1
end if  
next
1
  • The code is sound, except InStr() returns the character position if one is found where as you are using it as a boolean condition (True or False). Changing the If to If InStr(specialChars, testchar) > 0 Then will give you what you are expecting. Commented Nov 25, 2018 at 12:54

1 Answer 1

2

The problem here is InStr() as highlighted in the documentation;

Returns the position of the first occurrence of one string within another.

We can use this knowledge to create a boolean comparison by checking the return value of InStr() is greater than 0.

Dim testString: testString = "test@123"
Dim testchar, foundChar
Dim noOfSpecialChar: noOfSpecialChar = 0
Dim specialChars: specialChars = "*[@.^$|?#*+!)(_=-]."

For lngIndex = 1 To Len(testString)
  testchar = Mid(testString, lngIndex, 1)
  'Do we find the character in the search string?
  foundChar = (InStr(specialChars, testchar) > 0)
  If foundChar Then noOfSpecialChar = noOfSpecialChar + 1   
Next
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.