• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 217
  • 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 new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering 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