Prady
Prady

Reputation: 11310

substring help in c#

I have string qty__c which may or may not have a decimal point The code below gives me a System.ArgumentOutOfRangeException: Length cannot be less than zero.

qty__c = qty__c.Substring(0, qty__c.IndexOf("."));

How do i cater to if there is no "."?

Thanks

Upvotes: 0

Views: 267

Answers (5)

smirkingman
smirkingman

Reputation: 6358

Assuming you are looking for the decimal point in a number, which is at offset 3 both in '123.456' and '123', then one solution is

var index = (mystring & ".").IndexOf(".")

(Sorry about the VB, I'm not sure of C# syntax)

Upvotes: 0

Hemant Kumar
Hemant Kumar

Reputation: 4611

  var indexofstring=quantity.Indexof('.');
if(indexofstring!=-1)
{
quantity=quantity.SubString(0,indexofstring);
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500065

The simplest way is just to test it separately:

int dotIndex = quantity.IndexOf('.');
if (dotIndex != -1)
{
    quantity = quantity.Substring(0, dotIndex);
}

There are alternatives though... for example if you really wanted to do it in a single statement, you could either use a conditional operator above, or:

quantity = quantity.Split('.')[0];

or slightly more efficiently:

// C# 4 version
quantity = quantity.Split(new[] {'.'}, 2)[0];

// Pre-C# 4 version
quantity = quantity.Split(new char[] {'.'}, 2)[0];

(The second form effectively stops splitting after finding the first dot.)

Another option would be to use regular expressions.

On the whole, I think the first approach is the most sensible though. If you find you need to do this often, consider writing a method to encapsulate it:

// TODO: Think of a better name :)
public static string SubstringBeforeFirst(string text, string delimiter)
{
    int index = text.IndexOf(delimiter);
    return index == -1 ? text : text.Substring(0, index);
}

Upvotes: 6

Nayan
Nayan

Reputation: 3214

Use IndexOf method on that string. If returned value is -1, there is no character that was searched.

int index = mystring.IndexOf('.');

In your code, you are not checking the returned value of IndexOf. In the case where '.' is not present in the string, an exception will be thrown because SubString has been passed -1 as second parameter.

Upvotes: 1

Julien Hoarau
Julien Hoarau

Reputation: 49970

You just have to test if qty__c have a point in it before calling Substring :

var pointPos = qty__c.IndexOf('.');
if (pointPos != -1)
{
  qty__c = qty__c.Substring(0, pointPos);
}

Upvotes: 3

Related Questions