Search code examples
stringdelphiparsingdelphi-7

How to detect if a character from a string is upper or lower case?


I'm expanding a class of mine for storing generic size strings to allow more flexible values for user input. For example, my prior version of this class was strict and allowed only the format of 2x3 or 9x12. But now I'm making it so it can support values such as 2 x 3 or 9 X 12 and automatically maintain the original user's formatting if the values get changed.

The real question I'm trying to figure out is just how to detect if one character from a string is either upper or lower case? Because I have to detect case sensitivity. If the deliminator is 'x' (lowercase) and the user inputs 'X' (uppercase) inside the value, and case sensitivity is turned off, I need to be able to find the opposite-case as well.

I mean, the Pos() function is case sensitive...


Solution

  • Delphi 7 has UpperCase() and LowerCase() functions for strings. There's also UpCase() for characters.

    If I want to search for a substring within another string case insensitively, I do this:

    if Pos('needle', LowerCase(hayStack)) > 0 then
    

    You simply use lower case string literals (or constants) and apply the lowercase function on the string before the search. If you'll be doing a lot of searches, it makes sense to convert just once into a temp variable.

    Here's your case:

    a := '2 x 3';  // Lowercase x
    b := '9 X 12'; // Upper case X
    
    x := Pos('x', LowerCase(a)); // x = 3
    x := Pos('x', LowerCase(b)); // x = 3
    

    To see if a character is upper or lower, simply compare it against the UpCase version of it:

    a := 'A';
    b := 'b';
    
    upper := a = UpCase(a); // True
    upper := b = UpCase(b); // False