x


C# Check First Letter of String

Is there any way to just check what the first letter of a string is in c#? i can't find anything that can help.

more ▼

asked Oct 23, 2010 at 08:58 PM

DougWiiBoy gravatar image

DougWiiBoy
69 14 12 22

(comments are locked)
10|3000 characters needed characters left

5 answers: sort voted first

You can access chars of a string like arrays:

String s = "tada";

if (s[0] == 't'){
Debug.Log("tada");
}
more ▼

answered Oct 23, 2010 at 09:12 PM

Rasmus Schlnsen gravatar image

Rasmus Schlnsen
822 26 25 43

Be careful, this assumes s.Length > 0. If that assumptions might not hold, either check, or use:

if (s.StartsWith("t"))

which is more flexible too.

Jun 26, 2011 at 04:58 AM Waz
(comments are locked)
10|3000 characters needed characters left

C#:

String s = "tada";
Debug.Log("The first character of the string is: " + s.Substring(0, 1));

What the substring method does is retrieve a string within the string. The first parameter 0 is the starting index (starting position of the substring), and the number 1 is the amount of characters to grab.

more ▼

answered Oct 24, 2010 at 08:09 PM

MortenK84 gravatar image

MortenK84
63 3 2 8

Thank-you - after ensuring length is >1, works perfect!

Aug 29, 2013 at 04:01 PM GregMeach
(comments are locked)
10|3000 characters needed characters left
var myString = "abc";
print (myString[0]);
more ▼

answered Oct 23, 2010 at 09:10 PM

Eric5h5 gravatar image

Eric5h5
107k 52 180 648

(comments are locked)
10|3000 characters needed characters left

slice the string http://www.swishtutor.com/s/0020.htm then compare the result with what you want

more ▼

answered Oct 23, 2010 at 09:02 PM

Bravini gravatar image

Bravini
1.1k 16 18 40

sorry for being so pathetic but C# isn't my "best" language. So, i would go: if (myString.slice (put what here?)) { im looking to see if it starts with ! defining it as an admin command

Oct 23, 2010 at 09:08 PM DougWiiBoy

myString.slice(0,1) should do it

Jun 26, 2011 at 03:55 AM Bravini
(comments are locked)
10|3000 characters needed characters left

return (myString[0] >= 'A' && myString[0] <= 'Z') || (myString[0] >= 'a' && myString[0] <= 'z')

more ▼

answered Nov 21, 2012 at 04:13 PM

SARWAN gravatar image

SARWAN
151 32 30 43

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x8603
x641

asked: Oct 23, 2010 at 08:58 PM

Seen: 58583 times

Last Updated: Aug 29, 2013 at 04:01 PM