C#: How to Get First Char of a String

C#: how to get first char of a string?

Just MyString[0]. This uses the String.Chars indexer.

C#: how to get first character of a string?

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);

string[0] get first character from string

Casting a char to int in this way will give you its ASCII value which for 3 is equal to 51. You can find a full list here:

http://www.ascii-code.com/

You want to do something like this instead:

Char.GetNumericValue(input[0]);

How can I get the first character of a string?

Use the index of the character you want, so:
a[0]

For a complete answer:

char getFirstChar(string inString, char defaultChar)
{
if (string.IsNullOrEmpty(inString)) return defaultChar;
return inString[0];
}

Find the first character in a string that is a letter

There are several ways to do this. Two examples:

string s = "12345Alpha";
s = new string(s.TakeWhile(Char.IsDigit).ToArray());

Or, more correctly, as Baldrick pointed out in his comment, find the first letter:

s = new string(s.TakeWhile(c => !Char.IsLetter(c)).ToArray());

Or, you can write a loop:

int pos = 0;
while (!Char.IsLetter(s[pos]))
{
++pos;
}
s = s.Substring(0, pos);

How to Find the first character of a string in array

The following should work. There are a variety of string operators you can use, but here's a variation:

string[] array = {"one","two","three"};

foreach(string word in array) {
Console.WriteLine(word.Substring(0,1));
}

Also simply, word[0] would work.

shortest way to get first char from every word in a string

string str = "This is my style"; 
str.Split(' ').ToList().ForEach(i => Console.Write(i[0] + " "));


Related Topics



Leave a reply



Submit