c# String.Substring.Remove exception

moondaddy 916 Reputation points
2021-03-25T17:27:36.487+00:00

using c# 4.8 I get and exception when combining the string Substring and Remove methods.

this is the string I'm working with inside the square brackets (the value of the variable x):

[        "x": -89.05621501099995,]

and this is my code:

string test = x.Substring(13).Remove(x.Length-1);

I'm using x.Substring(13) to remove all text the the left of the minus sign.
and I'm using .Remove(x.Length-1) to remove the trailing comma.

But the remove method gives me this exception:

'x.Substring(13).Remove(x.Length-2)' threw an exception of type 'System.ArgumentOutOfRangeException'

Note: this works if I split this into 2 lines of code and add a new variable like this:

string strX = x.Substring(13);
strX = strX.Remove(strX.Length - 2);

but I have to apply the same process to a bunch of variables all in a loop with 100s of 1000s of loops server side, so I'm trying to optimize this.

Any ideas on the best way to approach this?

Thanks.

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2021-03-25T17:53:46.17+00:00

    Try another statement:

    string test = x.Remove( x.Length - 1 ).Substring( 13 );
    

    In case of new .NET 5 or Core, this should work too:

    string x = "        \"x\": -89.05621501099995,";
    string test = x[13..^1];
    

    If it is a part of JSON, then maybe use a special parser.


1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-03-25T17:48:27.283+00:00

    Try the following

    var someValue = " [        \"x\": -89.05621501099995,]";  
    var result = Regex.Replace(someValue, "[^0-9.-]", "");  
    

    Array example

    string[] values = {" [        \"x\": -89.05621501099995,]", "", " [        \"x\": -123.05,]" };  
      
    foreach (var value in values)  
    {  
        var fixedValue = Regex.Replace(value, "[^0-9.-]", "");  
        Console.WriteLine(string.IsNullOrWhiteSpace(fixedValue) ? "Empty value" : $"{value} -> {fixedValue}");  
    }  
    

    81661-f1.png

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.