我需要一些帮助来使用“;”将长字符串与文本框分开成几个不同字符串的数组。我正在编写一个简单的机器人程序,在此文本框中包含机器人运动的命令,但是当填写几个不同的 Action 时,机器人只会执行其中一个。这是盒子的代码。你对我的问题有什么建议?
public void ParseCommands(string txtS)
{
char[] delimiterChars = { ';' };
string text = txtS;
System.Console.WriteLine($"Original text: '{text}'");
string[] words = text.Split(delimiterChars);
System.Console.WriteLine($"{words.Length} words in text:");
}
private void cmdSend_Click(object sender, EventArgs e)
{
try
{
string txtS, lastMsg;
txtS = txtSend.Text;
byte[] bySend = Encoding.Default.GetBytes(txtS);
byte[] byReceive = new byte[255];
elfinSocket.Send(bySend, 0, txtS.Length, 0);
int intReceive = elfinSocket.Receive(byReceive, 0, byReceive.Length, 0);
Array.Resize(ref byReceive, intReceive);
lastMsg = Encoding.Default.GetString(byReceive);
lblRecieve.Text = lastMsg;
}
catch (SystemException error)
{
MessageBox.Show(error.Message);
}
}
最佳答案
看来你也应该使用你已经实现的工具。将命令字符串解构为多个部分并循环发送所有部分。您应该在 ParseCommands
方法中返回数组:
public string[]ParseCommands(string txtS)
{
char[] delimiterChars = { ';' };
string text = txtS;
System.Console.WriteLine($"Original text: '{text}'");
string[] words = text.Split(delimiterChars);
System.Console.WriteLine($"{words.Length} words in text:");
return words;
}
private void cmdSend_Click(object sender, EventArgs e)
{
string txtS, lastMsg;
txtS = txtSend.Text;
string[] commands = ParseCommands(txtS);
foreach (var element in commands)
{
byte[] bySend = Encoding.Default.GetBytes(element);
byte[] byReceive = new byte[255];
elfinSocket.Send(bySend, 0, txtS.Length, 0);
int intReceive = elfinSocket.Receive(byReceive, 0, byReceive.Length, 0);
Array.Resize(ref byReceive, intReceive);
lastMsg = Encoding.Default.GetString(byReceive);
lblRecieve.Text = lastMsg;
}
}
免责声明:似乎这将是一个持续时间更长的过程,因此您不会在标签中看到收到的响应消息的更新:
lblRecieve.Text = lastMsg;
您需要将其设为异步并将此代码放入单独的方法中。然后等待每次响应并将其写入标签。
异步版本可能如下所示:
private async void cmdSend_Click(object sender, EventArgs e)
{
string txtS, lastMsg;
txtS = txtSend.Text;
string[] commands = ParseCommands(txtS);
foreach (var element in commands)
{
string response = await Task.Run(()=>
{
byte[] bySend = Encoding.Default.GetBytes(element);
byte[] byReceive = new byte[255];
elfinSocket.Send(bySend, 0, txtS.Length, 0);
int intReceive = elfinSocket.Receive(byReceive, 0, byReceive.Length, 0);
Array.Resize(ref byReceive, intReceive);
return Encoding.Default.GetString(byReceive);
});
lblRecieve.Text = response;
}
}
这应该避免卡住 GUI
关于c# - 如何在C#中将字符串分隔成数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57799937/