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

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

相关推荐
染指111012 分钟前
142.Agent-多Agent框架-通过Skills实现多Agent
开发语言·人工智能·python·langchain·agents
天国梦14 分钟前
国密门禁品牌怎么选?2026年最新3个避坑要点
运维·服务器·数据库·python
好好学习O(∩_∩)O29 分钟前
[QT] 多线程moveToThread 和易踩的8个坑
开发语言·qt
我是人✓1 小时前
Java核心语法:作用域、循环与大数值处理
java·开发语言·后端
敲代码的乔帮主1 小时前
Python 3 现代类型标注入门
开发语言·python
夜之眷属1 小时前
PriorityQueue:for-each 遍历和 poll 取出,顺序一样吗?
java·服务器·数据结构·后端·算法
龙仔7251 小时前
RustDesk 自建服务器 Key 强校验配置笔记
运维·服务器·笔记
‎ദ്ദിᵔ.˛.ᵔ₎1 小时前
c++11:fuction包装器
开发语言·c++
kimnoic2 小时前
Python 爬虫的原理
开发语言·python
Fluxproxy2 小时前
Python爬虫异步提速终极方案|线程池ThreadPoolExecutor实战,告别单线程慢速爬取
开发语言·爬虫·python