简体   繁体   中英

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

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);
}

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);
}

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM