从字符串末尾对字符串进行子串

mar*_*zzz 23 .net c#

我需要从字符串的末尾删除两个字符.

所以:

string = "Hello Marco !"
Run Code Online (Sandbox Code Playgroud)

一定是

Hello Marco
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

Ale*_*dez 40

你可以做:

string str = "Hello Marco !";
str = str.Substring(0, str.Length - 2);
Run Code Online (Sandbox Code Playgroud)

  • @Alexander我不知道你说的是哪种语言,但在.net c#中,它是一种有效的方法.这也是适当的案例. (11认同)
  • 这解决了OP的情况,但实际上并没有回答如何从字符串末尾运行子字符串的问题.你的答案会截断字符串末尾的两个字母. (2认同)

Arm*_*yan 28

s = s.Substring(0, Math.Max(0, s.Length - 2))
Run Code Online (Sandbox Code Playgroud)

包括长度小于2的情况


Kir*_*man 9

C# 8 引入了允许您编写的索引和范围

str[^2..]
Run Code Online (Sandbox Code Playgroud)

这相当于

str.Substring(str.Length - 2, str.Length)
Run Code Online (Sandbox Code Playgroud)

事实上,这几乎就是编译器将生成的内容,因此没有开销。

请注意,ArgumentOutOfRangeException如果范围不在字符串内,您将得到一个。

  • 9年后,我迟到了一天:) (3认同)
  • 即使这是我真正想要的,问题也需要前 n-2 个字符,而不是最后 2 个字符。 (3认同)
  • 要获取前 n - 2 个字符,可以使用“str[..^2]”。2 甚至不需要是常量,所以你也可以写 `str[..^"test".Length]` (2认同)

Øyv*_*hen 7

关于什么

string s = "Hello Marco !";
s = s.Substring(0, s.Length - 2);
Run Code Online (Sandbox Code Playgroud)

  • @Armen - 这也不是问题,是吗?;) (6认同)

Fel*_*ano 5

I will trim the end for unwanted characters:

s = s.TrimEnd(' ', '!');
Run Code Online (Sandbox Code Playgroud)

To ensure it works even with more spaces. Or better if you want to ensure it works always, since the input text seems to come from the user:

Regex r = new Regex(@"(?'purged'(\w|\s)+\w)");
Match m = r.Match("Hello Marco   !!");
if (m.Success)
{
    string result = m.Groups["purged"].Value;
}
Run Code Online (Sandbox Code Playgroud)

With this you are safer. A purge based on the fact the last two characters has to be removed is too weak.