C#: how to get first character of a string?
Solution 1
You can use StringInfo class which is aware of surrogate pairs and multibyte chars.
var yourstring = "😂test"; // First char is multibyte char.
var firstCharOfString = StringInfo.GetNextTextElement(yourstring,0);
Solution 2
Use this:
str = str.Substring(0, 1);
or
str[0];
or
str.FirstOrDefault();
hippietrail
I'm a self taught hobby programmer with diverse and often changing interests. I learned BASIC on several microcomputers of the '80s and '90s then Z80 machine code on the Sinclair ZX Spectrum without an assembler then C and 68000 assembly on the Commodore Amiga then C++. Once Doom and Linux appeared I moved to the PC and started with scripting languages. I've moved from Perl to NodeJS, skipping Python and Ruby. I always find edge cases few other people hit in almost any project I get into. I worked as a professional C programmer from the mid nineties until the IT crash on Amiga and then PC. I'm very happy to be coding just for myself again.
Updated on June 14, 2022Comments
-
hippietrail almost 2 years
We already have a question about getting the first 16-bit
char
of a string.This includes the question code:
MyString.ToCharArray[0]
and accepted answer code:
MyString[0]
I guess there are some uses for that, but when the string contains text we hopefully are all aware that a single 16-bit char cannot hold a character, even in the restricted sense where we actually mean "codepoint".
I am a programmer but not a C# programmer. I am just trying to help an online colleague fix such a bug, in case you feel this is too basic a question.
So if we have a string in C# in a
char
array, encoded in correct UTF-16, possibly including a surrogate pair as the first character/codepoint and thus potentially consisting of twochar
s, how do I get that first character?(I naïvely assume Microsoft provides a string function for this and that I don't have to manually check for surrogate pairs.)