C#去掉字符串首尾字符

以下是多种不同的实现方法来去除C#字符串的首尾字符:

1、使用Substring方法:

string input = "Hello World!";
string output = input.Substring(1, input.Length - 2);

2、使用Remove方法:

string input = "Hello World!";
string output = input.Remove(0, 1).Remove(input.Length - 2, 1);

3、使用Trim方法:

string input = "Hello World!";
string output = input.Trim(input[0], input[input.Length - 1]);

4、使用正则表达式:

string input = "Hello World!";
string pattern = $"^{input[0]}|{input[input.Length - 1]}$";
string output = Regex.Replace(input, pattern, "");

5、使用StringBuilder:

string input = "Hello World!";
StringBuilder builder = new StringBuilder(input);
builder.Remove(0, 1).Remove(input.Length - 2, 1);
string output = builder.ToString();

 

posted @   每天进步多一点  阅读(814)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤
历史上的今天:
2022-05-30 有趣的css—隐藏元素的7种思路
2016-05-30 Sql 行转列、列转行及分页
2016-05-30 C#中问号的使用
点击右上角即可分享
微信分享提示