简体   繁体   English

如何删除字符串中的最后 5 个字符?

[英]How do i remove the last 5 characters in a string?

I was trying to remove the last 5 characters in a string but i'm having a error我试图删除字符串中的最后 5 个字符,但出现错误

  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.错误:附加信息:索引和长度必须引用字符串中的位置。

You problems is the misunderstanding and usage of the parameters of Substring你的问题是Substring参数的误解和使用

The first parameter第一个参数

The zero-based starting character position of a substring in this instance.在此实例中,substring 的从零开始的起始字符 position。

The second parameter is第二个参数是

The number of characters in the substring. substring 中的字符数。

You would need to supply the Length of the string, minus the size that needed to be removed您需要提供字符串的Length ,减去需要删除的大小

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另一种更强大的方法是通过端口分隔符Split

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注意:即使没有提供端口,这也会起作用,并在 null 字符串上返回 null,如果没有提供端口,则返回字符串


Or, if you are using.Net Core 3+ you could take advantage of IPEndPoint.Parse then call Address或者,如果您使用的是.Net Core 3+,您可以利用IPEndPoint.Parse然后调用Address

Converts an IP network endpoint (address and port) represented as a string to an IPEndPoint instance.将表示为字符串的 IP 网络端点(地址和端口)转换为 IPEndPoint 实例。

var result = IPEndPoint.Parse(a).Address

Note : To add even more fault-tolerance you could use the IPEndPoint.TryParse method注意:要添加更多容错,您可以使用IPEndPoint.TryParse方法

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM