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

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

相关推荐
稳联技术老娜2 小时前
DeviceNet主站怎么连接西门子PLC,Profinet网关配置手册(那智机器人)
服务器·网络·数据库
石山代码2 小时前
ArrayList / HashMap / ConcurrentHashMap
java·开发语言
9分钟带帽2 小时前
linux_系统开机自动执行shell脚本
linux·服务器
程序大视界2 小时前
【Python系列课程】Python正则表达式(下):环视、命名分组与日志实战
开发语言·python·正则表达式
枫叶v.3 小时前
Agent 分层存储架构设计:从记忆方法到中间件选型
开发语言·python
消失在人海中3 小时前
oracle 数据库多表关联查询
服务器·数据库·oracle
嵌入式小能手4 小时前
飞凌嵌入式ElfBoard-进程间的通信之命名管道
linux·服务器·算法
sleven fung4 小时前
MinerU与BabelDOC与KTransformers与OpenAI API库
开发语言·python·ai·langchain
萤萤七悬4 小时前
【Python笔记】AI帮实现CLI工具-使用argparse.ArgumentParser接收命令参数
开发语言·笔记·python
iCxhust4 小时前
C# 命令行指令 查看二进制文件
开发语言·单片机·嵌入式硬件·c#·proteus·微机原理·8088单板机