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 方法来删除字符串末尾的指定字符。

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

相关推荐
Miracle&13 小时前
在Linux VirtualBox中安装系统失败
linux·运维·服务器
熬夜敲代码的小N13 小时前
Python基础入门:环境配置全指南+核心语法解析
开发语言·python
嫂子开门我是_我哥13 小时前
第十八节:项目实战2:简易通讯录(面向对象+文件持久化实现)
开发语言·python
MediaTea13 小时前
Python:_sentinel 命名约定
开发语言·python·sentinel
ShoreKiten13 小时前
ctfshow-web316
运维·服务器·前端
茉莉玫瑰花茶13 小时前
C++17 详细特性解析(中)
开发语言·c++
shehuiyuelaiyuehao13 小时前
String的杂七杂八方法
java·开发语言
开发者小天13 小时前
python返回随机数
开发语言·python
13 小时前
java关于时间类
java·开发语言
lly20240613 小时前
C 标准库 - <stdlib.h>
开发语言