How to detect illegal characters in a string? RRS feed

  • Question

  • Hi,

    How to detect if there are any illegal characters in a string? In the input keyboard there are many characters that cant be used to create a filename eg characters like \ / : * ? " |. Besides these, there are quite a number of others.

    So, how do I detect them?


    • Edited by ylk56 Wednesday, May 23, 2012 1:53 PM
    Wednesday, May 23, 2012 1:51 PM


All replies

  • Easiest and most reliable way:  Try to create the file and see if it succeeds.

    Harder, you can use something like strcspn (or its wide char brethren) to detect such illegal characters.

    Wednesday, May 23, 2012 2:43 PM
  • The variants available for strcspn are CString::FindOneOf and std::string::find_first_of.

    Microsoft MVP (Visual C++)

    Polymorphism in C

    • Proposed as answer by Darran Rowe Thursday, May 24, 2012 10:16 AM
    • Marked as answer by ylk56 Thursday, May 24, 2012 11:21 AM
    Wednesday, May 23, 2012 3:06 PM
  • you can also check with ASCII value for each char. If it is valid range, you can accept. otherwise, you can ignore the chars. 

    Thanks and Regards Selvam http://www15.brinkster.com/selvamselvam/

    Wednesday, May 23, 2012 4:13 PM
  • Thanks. Does someone know the ASCII range for all the illegal characters that can't be a part of a filename?

    I tried searching on the web but couldn't find it yet.

    Thursday, May 24, 2012 6:48 AM
  • \ / : * ? " < > |

    Microsoft MVP (Visual C++)

    Polymorphism in C

    Thursday, May 24, 2012 6:56 AM
  • You can use std::regex: "[(\\)(/)(:)(*)(?)(")(<)(>)(|)]". If this matches, you also have the capture groups so you can show a message with the invalid characters...
    Thursday, May 24, 2012 7:03 AM