如何为字符串类型编写switch语句
本文关键字:switch 语句 类型 字符串 | 更新日期: 2023-09-27 18:05:43
我使用串行端口连接设备,该设备返回给我":gs# "字符串。经过长时间的检查,我几乎可以肯定问题出在切换条件,即,我的程序从不进入大小写,总是进入默认。我在一个文本框中打印了接收到的字符串,它是":GS #"!我很困惑。我错在哪里?
下面是我的代码:char[] lxCMD = new char[8];
.
.
.
private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
serialPort.Read(lxCMD, 0, lxCMD.Length);
this.Invoke(new EventHandler(UpdateVar));
}
private void UpdateVar(object sender, EventArgs e)
{
string strRecieved = "Ack";
if (lxCMD[0] != 0x6)
{
strRecieved = new string(lxCMD);
}
textBox1.AppendText(strRecieved); // This line prints :GS# correctly!
textBox1.AppendText(Environment.NewLine);
switch(strRecieved)
{
case ":GS#":
serialPort.Write("20:08:18#");
textBox1.AppendText("1:");
textBox1.AppendText(Environment.NewLine);
break;
case "Ack":
serialPort.Write("1");
textBox1.AppendText("2:");
textBox1.AppendText(Environment.NewLine);
break;
default:
textBox1.AppendText("Nothing");
break;
}
}
正如在评论中指出的那样,您保存读取字节的char
数组长度为8个字符。当你将数组转换为字符串时它会创建一个长度为8的字符串,你可以通过调用strRecieved.Length
来检查例如:
textBox1.AppendText(strRecieved); // This line prints :GS# correctly!
textBox1.AppendText(Environment.NewLine);
Console.Out.WriteLine(strRecieved.Length); //or any other means of output - will output 8
这意味着字符串中有一些不可打印的字符(ASCII表为空)。因此情况不匹配!
由于串行端口的Read
方法返回读取的字节数,尝试使用它来获得正确的子字符串。例如(I Think this work):
char[] lxCMD = new char[8];
var bytesRead = 0;
.
.
.
private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
bytesRead = serialPort.Read(lxCMD, 0, lxCMD.Length);
this.Invoke(new EventHandler(UpdateVar));
}
private void UpdateVar(object sender, EventArgs e)
{
string strRecieved = "Ack";
if (lxCMD[0] != 0x6)
{
strRecieved = new string(lxCMD);
strRecieved = strRecieved.SubString(0, bytesRead)
}
textBox1.AppendText(strRecieved); // This line prints :GS# correctly!
textBox1.AppendText(Environment.NewLine);
switch(strRecieved)
{
case ":GS#":
serialPort.Write("20:08:18#");
textBox1.AppendText("1:");
textBox1.AppendText(Environment.NewLine);
break;
case "Ack":
serialPort.Write("1");
textBox1.AppendText("2:");
textBox1.AppendText(Environment.NewLine);
break;
default:
textBox1.AppendText("Nothing");
break;
}
}
将if语句中的string strreceived初始化为:
strRecieved = new string(chars.TakeWhile(c => c != ''0').ToArray());
问题是,如果输入长度不是8,则字符数组在末尾保存多个'0字符。
下面的测试演示了它:
[Test]
public void stringConstructor_CharArrayWithSomeEmptyValues_StringWithoutEmptyValues()
{
var expected = "test";
var chars = new char[expected.Length+42];
chars[0] = expected[0];
chars[1] = expected[1];
chars[2] = expected[2];
chars[3] = expected[3];
var str = new string(chars.TakeWhile(c => c != ''0').ToArray());
Assert.AreEqual(expected, str);
str = new string(chars,0,chars.Length);
Assert.AreNotEqual(expected, str);
}