Ben*_*ton 3 .net c# string listbox
i am trying to separate the IP from the port in a list box. but i am only leaving the port number and ":" how would i make it so the ":" is removed and only the IP is left.
ips look like this:
192.168.0.12:80
192.168.0.2:123
192.168.0.3:1337
for (int i = 0; i < lb.Items.Count; i++)
{
string item = lb.Items[i] as string;
item = item.Substring(item.LastIndexOf(":"));
lb.Items[i] = item;
}
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以拆分字符串:
string ip = item.Split(":")[0]
Run Code Online (Sandbox Code Playgroud)
或者您可以创建一个 Uri 对象并从中提取 Host 值
You could parse it into a Uri and then inspect the Host value:
String ip = "192.168.0.3:1337";
Uri uri = new Uri("http://" + ip);
MessageBox.Show(uri.Port.ToString()); //shows 1337
MessageBox.Show(uri.Host.ToString()); //shows 192.168.0.3
Run Code Online (Sandbox Code Playgroud)
这具有确保 URI 有效的额外好处,并且适用于不包含 a 的地址,:而 usingIndexOf(':')则不会,因此您必须进行额外检查以查看字符串.Contains是否首先