最近在写一个串口监控的上位机软件,由于用到串口收发程序,自然就要面对空格符,\r\n 这些特殊字符的困扰,那么,在c#平台下,我们应该有高效的去掉这些特殊字符呢?
1 String.Trim方法
String.Trim() 方法去除字符串的头和尾的空格,不幸运的是. 这个Trim方法不能去除字符串中间的C#空格。
比如上位机发送 string textStr = " This is my first\nstring\r\n is\t too long to ";
string textStr = " This is my first\nstring\r\n is\t too long to ";
string trim = textStr.Trim();
执行'Trim' 后,输出结果:
"This is my first\nstring\r\n is\t too long to"
头尾空格去掉了,但中间的空格还在呀?总不能就这样发给MCU吧,那MCU端解码不是很头大?
2 String.Replace 方法
String.Replace 也是平常经常用到的方法, 但是这需要你通过调用多个方法来去除个别C#空格:
string trim = textStr.Replace( " ", "" ); /*去掉空格,包括中间的空格*/
trim = trim.Replace( "\r", "" ); /*去掉\r */
trim = trim.Replace( "\n", "" ); /*去掉\n */
trim = trim.Replace( "\t", "" ); /*去掉\t */
调用4次Replace, 可以达到我们想要的目的。
3 使用正则表达式
所用正则表达式,可以说是最高效的,但这要有点编程功底了。
string trim = Regex.Replace( textStr, @"\s", "" );
输出:
"Thisismyfirststringistoolongto"
前后空格,中间空格和特殊字符,全部去得很干净。
上面三种方法,是我们在数据处理时,经常用到的方法。
顺便说下,正则表达中,"\s" 是指空白,包括空格、换行、tab缩进等所有的空白。