怪物奇妙物语

宇宙无敌超级美少男的怪物奇妙物语

首页 新随笔 联系 管理
  819 随笔 :: 0 文章 :: 2 评论 :: 16万 阅读

Trim()的使用

1. 删除字符串两端的特殊符号:

string str = "***This string has special characters***";
char[] trimChars = new char[] { '*', '!' };
string trimmed = str.Trim(trimChars); // trimmed will be "This string has special characters"

2. 清理文本输入框中的内容:

string input = " John Doe ";
string trimmed = input.Trim(); // trimmed will be "John Doe"
// Trim() removes whitespace by default, but you can also specify other characters to trim.
string trimmedWithSpecificChars = input.Trim(new char[] { ' ', ',' }); // trimmedWithSpecificChars will be "John,Doe"

3. 比较两个字符串,忽略空格和其他符号:

string str1 = "This is a string";
string str2 = " This is a string ";
// Using Trim() ensures that the strings are compared without any extra characters.
if (str1.Trim().Equals(str2.Trim()))
{
Console.WriteLine("The strings are equal.");
}

4. 从文件名中删除扩展名:

string fileName = "my-file.txt";
string trimmedFileName = fileName.TrimEnd(new char[] { '.', 't', 'x', 't' }); // trimmedFileName will be "my-file"

5. 从路径中删除多余的斜杠:

string path = "\\\\server\\share\\folder\\\\";
string trimmedPath = path.Trim('\\'); // trimmedPath will be "\\server\share\folder"

6. 处理 CSV 文件中的数据:

string csvLine = "123,John Doe,New York,USA";
string[] columns = csvLine.Split(',');
// Trim() removes any extra spaces from each column value.
string name = columns[1].Trim();
string city = columns[2].Trim();
string country = columns[3].Trim();

7. 从 HTML 代码中删除空格:

string html = "<html> <head> <title>This is a title</title> </head> <body> <h1>This is a heading</h1> </body> </html>";
string trimmedHtml = html.Replace(" ", ""); // trimmedHtml will be "<html><head><title>Thisisatititle</title></head><body><h1>Thisisheading</h1></body></html>"
// This is just a basic example. You can use more sophisticated methods to remove whitespace from HTML code.

8. 从 XML 代码中删除注释:

string xml = "<xml> <element>This is an element</element> </xml>";
string trimmedXml = xml.Replace("", ""); // trimmedXml will be "<xml><element>Thisisanelement</element></xml>"
// This is just a basic example. You can use more sophisticated methods to remove comments from XML code.
posted on   超级无敌美少男战士  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
历史上的今天:
2021-06-29 mybatis环境搭建
2021-06-29 eclipse-查看继承层次图/继承实现层次图
2021-06-29 eclipse中的Quick Type Hierarchy快速类型层次结构
2021-06-29 eclipse中的Quick Outline 快速大纲
2021-06-29 短语Quick Outline
2021-06-29 Expression Language表达中的参数访问对象
2021-06-29 el表达式点操作符和方括号操作符的区别
点击右上角即可分享
微信分享提示