我需要从字符串的末尾删除两个字符.
所以:
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)
Arm*_*yan 28
s = s.Substring(0, Math.Max(0, s.Length - 2))
Run Code Online (Sandbox Code Playgroud)
包括长度小于2的情况
C# 8 引入了允许您编写的索引和范围
str[^2..]
Run Code Online (Sandbox Code Playgroud)
这相当于
str.Substring(str.Length - 2, str.Length)
Run Code Online (Sandbox Code Playgroud)
事实上,这几乎就是编译器将生成的内容,因此没有开销。
请注意,ArgumentOutOfRangeException如果范围不在字符串内,您将得到一个。
关于什么
string s = "Hello Marco !";
s = s.Substring(0, s.Length - 2);
Run Code Online (Sandbox Code Playgroud)
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.
| 归档时间: |
|
| 查看次数: |
92975 次 |
| 最近记录: |