Search code examples
c#stringexceptionsubstring

c# substring method error when setting end parameter


I am trying to extract part of a string from itself. I get de string from an http request. I want to slice from position 17, to its Length - 3. Here is my code in c#:

var response = await responseURI2.Content.ReadAsStringAsync();
Debug.WriteLine(response);
Debug.WriteLine(response.GetType());
Debug.WriteLine(response.Length);
int length = (response.Length) - 3;
Debug.WriteLine(length);
try{
    var zero = response.Substring(17, length);
    Debug.WriteLine(zero);
}
catch
{
    Debug.WriteLine("Not able to do substring");
}

This is the output:

[0:] "dshdshdshdwweiiwikwkwkwk..."
[0:] System.String
[0:] 117969
[0:] 117966
[0:] Not able to do substring

Any ideas of why it cannot do Substring correctly? If I only do response.Substring(17) it works ok. However, when I try to cut from the end, it fails.


Solution

  • When working with indexes, say, you want to obtain substring from 17th position up to 3d from the end, you can use ranges instead of Substring:

    var zero = response[17..^3];
    

    If you insist on Substring you have to do the arithmetics manually:

    var zero = response.Substring(17, response.Length - 17 - 3);