Checking the first character in a string

I have a string variable that I need to check the first character on.

How do I check if the variable var1 has a "-" for the first character?
RosanneParnellAsked:
Who is Participating?
 
Timbo87Commented:
I've found that using a character based indexer yields almost twice the performance of Substring for extracting a single character.

if(var1[0] == '-')
     // first character is -
0
 
dfu23Commented:
if (var1.InString("-") == 0) {
 // do whatever
}
0
 
RosanneParnellAuthor Commented:
Will this work for only the first character or is this going to be true if there are other "-" in my string?
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
tusharashahCommented:
Try this:

----------------------------------------
if( var.Substring(0,1) == "-" )
{
    .....
}
----------------------------------------

-tushar
0
 
dfu23Commented:
I'm sorry, I meant to use IndexOf

so the code example would be:

if (var1.IndexOf("-") == 0) {
 // do whatever
}

This searches the string from left to right and will return the index of first instance of that character. So if it finds a dash "=" at the first index (index 0) the if statement will be true. If it finds it later in the string or not at all in the string this will not be true.

tusharashah's comment would work but would generate an error if the string was zero length ... ""
0
 
dfu23Commented:
Once again ... if the string is zero length this will throw an error ... might want to put it in a try catch block.
0
 
msdixonCommented:
dfu23

a try / catch block is very inefficient. it's better to check the length first.

if (var1.Length > 0)
{
   // check if it starts with a dash
   // perform your action here....
}


on a side note...
there's also the StartsWith method

if (var1.StartsWith("-"))
{
   // do stuff
}

i haven't done any performance tests... but sometimes, it's good to know multiple ways of doing the same thing.
0
 
dfu23Commented:
Cool, I learned something new ... never knew there was a StartsWith method ...
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.