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.
CodePudding user response:
When working with indexes, say, you want to obtain substring from 17
th position up to 3
d 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);
CodePudding user response:
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);