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

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

相关推荐
多多鼠9 小时前
System Prompt 的“版本漂移”问题:从变更管理到 A/B 测试体系
开发语言·网络·人工智能·python·langchain
WiChP9 小时前
【V0.1B16】从零开始的2D游戏引擎开发之路
开发语言·算法·游戏引擎
华允物联-HUAIOT9 小时前
串口路由器是什么?带串口的工业联网设备科普
服务器
菜鸟学编程o9 小时前
Linux常见指令
linux·运维·服务器
孙启超10 小时前
【AI开发之Rust】第 8 课:泛型、trait 与 trait 对象
开发语言·后端·rust
2501_9336707910 小时前
经营财务岗技能栈拆解:Excel、SQL、BI、预算分析怎么准备
开发语言
数据狐(Datafox)11 小时前
1688商品列表API接口解析(附 JSON 样例)
java·开发语言·数据库·爬虫·json
小此方11 小时前
Linux网络(十二):HTTP短连接与长连接:从Connection机制到Cookie、Session,彻底理解HTTP的无状态
服务器·网络·http
专注仿真11 小时前
CMO模型文档-活动单元基类
c#·模型·cmo·活动单元基类
小灰灰搞电子11 小时前
Rust Once 、OnceLock、LazyLock 一次性初始化详解
开发语言·后端·rust