Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 218
  • 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
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

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

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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