C#去掉字符串最后一个字符

可以直接去掉 C# 字符串的最后一个字符。有几种方法可以实现这个功能:

方法1:使用 Substring 方法

csharp 复制代码
string str = "Hello World";
string result = str.Substring(0, str.Length - 1);
Console.WriteLine(result); // 输出 "Hello Worl"

这种方法是获取除了最后一个字符之外的所有字符,并将其赋值给新的字符串变量 result

方法2:使用 Remove 方法

csharp 复制代码
string str = "Hello World";
string result = str.Remove(str.Length - 1);
Console.WriteLine(result); // 输出 "Hello Worl"

这种方法使用 Remove 方法来删除字符串的最后一个字符。Remove 方法会返回从指定位置开始删除指定字符数的新字符串。

方法3:使用 TrimEnd 方法

csharp 复制代码
string str = "Hello World";
string result = str.TrimEnd(str[str.Length - 1]);
Console.WriteLine(result); // 输出 "Hello Worl"

这种方法使用 TrimEnd 方法来删除字符串末尾的指定字符。

以上三种方法都可以实现去掉字符串的最后一个字符。您可以根据自己的需求选择其中之一来使用。

相关推荐
为思念酝酿的痛29 分钟前
POSIX信号量
linux·运维·服务器·后端
AI玫瑰助手1 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
油炸自行车1 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
周杰伦fans1 小时前
C# 踩坑 CS8370:Switch Expression 在 C# 7.3 不可用及三种解决方案
c#
肩上风骋1 小时前
C++14特性
开发语言·c++·c++14特性
隔窗听雨眠1 小时前
Nginx网关响应慢排查手记
java·服务器·nginx
人还是要有梦想的2 小时前
linux下用搜狗输入法,中英文切换
linux·运维·服务器
9分钟带帽2 小时前
linux_通过NFS挂载远程服务器的硬盘
linux·服务器
JAVA社区3 小时前
Java高级全套教程(十)—— SpringCloudAlibaba超详细实战详解
java·开发语言·spring cloud·面试·职场和发展
弥树子3 小时前
踩坑记录:服务器内网调用接口,真实请求URL与官方公开URL不一致问题排查
开发语言·php