Stack Overflow Asked by Ktulu Hala on December 5, 2021
I was trying to remove the last 5 characters in a string but i’m having a error
string a = "192.168.0.225:5010";
int b = a.Length;
string c = a.Substring(b, 5);
MessageBox.Show(c.ToString());
Error : Additional information: Index and length must refer to a location within the string.
Use this
string a = "192.168.0.225:5010";
int b = a.Length;
string c = a.Substring(0, b-5); // change this
MessageBox.Show(c);
Answered by mrbm on December 5, 2021
You problems is the misunderstanding and usage of the parameters of Substring
The first parameter
The zero-based starting character position of a substring in this instance.
The second parameter is
The number of characters in the substring.
You would need to supply the Length
of the string, minus the size that needed to be removed
string a = "192.168.0.225:5010";
var result = a.Substring(0, a.length - 5);
// or
var result = a.Substring(a.length - 5);
Note : This is a one way street to fail-town if the port size differs or is not available
Another slightly more robust way would be to Split
by the port separator
Splits a string into substrings that are based on the characters in the separator array.
var result = a?.Split(':')[0]
Note : This will work even if no port is supplied and return null on a null string, and the string if no port is supplied
Or, if you are using .Net Core 3+ you could take advantage of IPEndPoint.Parse
then call Address
Converts an IP network endpoint (address and port) represented as a string to an IPEndPoint instance.
var result = IPEndPoint.Parse(a).Address
Note : To add even more fault-tolerance you could use the IPEndPoint.TryParse
method
Answered by TheGeneral on December 5, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP