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

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

相关推荐
189228048612 分钟前
NV265固态MT29F32T08GSLBHL8-24QMES:B
大数据·服务器·人工智能·科技·缓存
Vinton_Liu12 分钟前
NAT 类型详解:四种 NAT 的数据流与原理解析
运维·服务器
想唱rap13 分钟前
五种IO模型和非阻塞IO
linux·运维·服务器·网络·数据库·tcp/ip
周末也要写八哥17 分钟前
在C++中使用预定义宏
开发语言·c++·算法
Data_Journal26 分钟前
使用Python lxml轻松进行网络爬取
开发语言·php
xcLeigh40 分钟前
IoTDB JDBC 完整使用教程:连接、查询、批处理与字符集配置
开发语言·数据库·qt·iotdb·查询·批处理·连接
学会870上岸华师43 分钟前
C 语言程序设计——第一章课后编程题
c语言·开发语言·学习·算法
小小编程路44 分钟前
新手快速学 Python 极简速成指南
开发语言·c++·python
方安乐1 小时前
交换机的自学机制
运维·服务器·网络
rabbit_pro1 小时前
SpringBoot3集成Langchain4j使用Ollama
java·开发语言