7

I have a string, from which I want to extract one character that is needed to be used in a Case statement. The thing is the Case only takes Char values and not string values. So how do I convert a single string character to a char?

3 Answers 3

12

Use the string as a character array (1-based), and use the index of the character you want to use in the case statement. For instance, if you want to use the first character:

case MyString[1] Of // ... end; 

NB make sure you check the the string is of at least that length before you use the subscript, or you'll get an access violation.

Sign up to request clarification or add additional context in comments.

3 Comments

Hands up if you have a function in your personal library of code with a signature like the following: function StrToChar(const S: string; Index: Integer = 1; Default: Char = ' '): Char;
Nice edit, I do C# and Delphi, and always end up with a mental block on zero and 1 based, have to check every time I switch
Shortest is this: c := Copy(s + ' ', 1, 1)[1];
3

Since string became 0-based on mobile platforms, there is also an always-safe way to get a char from single-character string.

myString[Low(myString)] 

Comments

3

Since delphi became cross-platform I would use 0-based string access using TStringHelper class out of unit System.SysUtils:

case MyString.Chars(0) Of // ... end; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.