Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 216
  • Last Modified:

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?
0
RosanneParnell
Asked:
RosanneParnell
1 Solution
 
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
 
tusharashahCommented:
Try this:

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

-tushar
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 
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:
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

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now