2

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.

4
  • 3
    Perhaps you can figure this out when you remove the catch and just read the exception that is thrown. Commented Sep 1, 2022 at 10:08
  • Say you have a string that is 21 characters long. Your code says "the length is 18" (21 - 3 = 18). Then you're saying "give me 18 characters from position 17 onwards." 18 + 17 = 35, the string only contains 21, Houston, we have a problem. Commented Sep 1, 2022 at 10:08
  • You should probably read the docs. Commented Sep 1, 2022 at 10:09
  • Thanks, i should have read the docs indeed! Commented Sep 1, 2022 at 10:22

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

That's the best way, i forgot about ranges since i still cant work with C#8. But to make your answer complete you need to mention that OP used the second parameter of Substring like it was for the endIndex(so needs endIndex - startIndex to calculate length).
0

From the Docs:

public string Substring (int startIndex, int length);

Substring takes the parameters int startIndex and int length

When you don't start from the beginning of the string, you need calculate the remaining length by deducting the startIndex from your length.

Try

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.