[英]Removing the first and last character of a string C#
For an exercise on codewars I had to remove the first and last character of a string.对于 codewars 的练习,我必须删除字符串的第一个和最后一个字符。 After some fidling about I found a solution that works:
经过一番折腾,我找到了一个有效的解决方案:
public static string Remove_char(string s)
{
return s.Substring(1, s.Length - 2);
}
My question is why do I have to use -2 instead of -1 at the end of the return line when I only want to remove the last character?我的问题是当我只想删除最后一个字符时,为什么我必须在返回行的末尾使用 -2 而不是 -1 ?
因为第二个参数不是您想要子字符串的偏移量,它是所需子字符串的长度。
The Substring counts the length starting at the first index. Substring 计算从第一个索引开始的长度。
So if you remove the first character the string already has s.Length-1
.因此,如果您删除第一个字符,该字符串已经具有
s.Length-1
。 If you now want to remove the last character as well you need to use s.Length-2
.如果您现在还想删除最后一个字符,则需要使用
s.Length-2
。
数组索引从 0 开始,如果你跳到最后一个索引,那么你需要 s.Length-1,即数组的长度 - 1。所以你的问题是你需要删除最后一个字符,这就是为什么你添加了 s.Length-2
因为您想返回从初始字符串的第二个到倒数第二个字符的子字符串,即不是第一个(第 0 个字符)也不是最后一个(长度为 1 个字符)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.