【问题标题】:visual studio c# split string into variables [closed]Visual Studio C#将字符串拆分为变量[关闭]
【发布时间】:2017-07-25 13:26:48
【问题描述】:

我希望 somone 可以帮助我,我使用 Visual Studio IDE 创建了一个界面,该界面也连接到了一个 arduino。我在读取数据时遇到了问题,但是已经解决了。从 arduino 发送的数据看起来像这样 1,2,3,我遇到的问题是,每次我尝试将字符串拆分为单独的变量时,它似乎都不起作用。我将在下面发布这两个部分的代码。如果有人能帮我解决这个问题会很棒

视觉工作室:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        public SerialPort myport;

        int irisvalue;

        string myString;
        String s;

        //string[] words;

        String readString;

        String firstValue;
        String secondValue;
        String thirdValue;

        public Form1()
        {
           InitializeComponent();
            //Load += new EventHandler(Form1_Load);
            connectbtn.Text = "Connect";
            disconnect.Text = "Disconnect";
            this.connectbtn.Click += new EventHandler(connectbtn_Click);
            this.disconnect.Click += new EventHandler(disconnect_Click);
            this.iris1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.iris1_MouseDown);
            this.iris1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.iris1_MouseUp);
            this.iris2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.iris2_MouseDown);
            this.iris2.MouseUp += new System.Windows.Forms.MouseEventHandler(this.iris2_MouseUp);
            this.focus1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.focus1_MouseDown);
            this.focus1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.focus1_MouseUp);
            this.focus2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.focus2_MouseDown);
            this.focus2.MouseUp += new System.Windows.Forms.MouseEventHandler(this.focus2_MouseUp);

        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


         void connect()
        {

            myport = new SerialPort();
            myport.BaudRate = 9600;
            myport.PortName = "COM3";
            myport.Open();

        }

        void read()
        {


            myport.DataReceived += (sender, e) =>
            {
                if (e.EventType == SerialData.Chars)
                    s = myport.ReadLine();

            };

        }

        void discon()
        {


            myport.Close();

        }

        private void disconnect_Click(object sender, System.EventArgs e)
        {
            discon();
            if (myport.IsOpen)
            {

            }
            else
            {

                connectbtn.Text = "Connect";
                disconnect.BackColor = default(Color);
                connectbtn.BackColor = default(Color);
            }
            }

            private void connectbtn_Click(object sender, System.EventArgs e)
        {
            connect();

            if (myport.IsOpen)
            {

                connectbtn.Text = "Connected";
                connectbtn.BackColor = Color.Green;
                //Load += new EventHandler(Form1_Load);
                Form1_Load();
                disconnect.BackColor = Color.Red;
                disconnect.Text = "Disconnect";
                read();
                //s = myport.ReadLine();





            }
            else
            {
                connectbtn.Text = "Error";
                connectbtn.BackColor = Color.Red;
            }


        }


        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        private void iris1_MouseDown(object sender, MouseEventArgs e)
        {
            //Console.WriteLine("Hello");

            irisvalue = 1;
            myString = irisvalue.ToString();
            Form1_Load();

        }

        private void iris1_MouseUp(object sender, MouseEventArgs e)
        {

            irisvalue = 0;
            myString = irisvalue.ToString();
            Form1_Load();
        }



        private void iris2_MouseDown(object sender, MouseEventArgs e)
        {
            irisvalue = 2;
            myString = irisvalue.ToString();
            Form1_Load();

        }


        private void iris2_MouseUp(object sender, MouseEventArgs e)
        {
            irisvalue = 0;
            myString = irisvalue.ToString();
            Form1_Load();

        }

        private void focus1_MouseDown(object sender, MouseEventArgs e)
        {
            irisvalue = 3;
            myString = irisvalue.ToString();
            Form1_Load();

        }


        private void focus1_MouseUp(object sender, MouseEventArgs e)
        {
            irisvalue = 0;
            myString = irisvalue.ToString();
            Form1_Load();


        }

        private void focus2_MouseDown(object sender, MouseEventArgs e)
        {
            irisvalue = 4;
            myString = irisvalue.ToString();
            Form1_Load();

        }

        private void focus2_MouseUp(object sender, MouseEventArgs e)
        {

            irisvalue = 0;
            myString = irisvalue.ToString();
            Form1_Load();
        }



        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public void Form1_Load()
            {





            readString += s;


            if (readString.Length > 0)
            {

                int commaIndex = readString.IndexOf(',');
                int secondCommaIndex = readString.IndexOf(',', commaIndex + 1);

                firstValue = readString.Substring(0, commaIndex);
                secondValue = readString.Substring(commaIndex + 1, secondCommaIndex);
                thirdValue = readString.Substring(secondCommaIndex + 1); // To the end of the string

                //int x = Int32.Parse(firstValue);
                //int y = Int32.Parse(secondValue);
               // int z = thirdValue.toInt();



                Console.WriteLine(firstValue);
                Console.WriteLine(secondValue);
                Console.WriteLine(thirdValue);
            }


            myport.WriteLine(myString);




        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


    }

} 

阿杜诺:

String readString;

int INA = 11;
int INB = 9;
int INC = 7;
int IND = 5;

int ledpin = 3;

int inPin = 14;
int inPin2 = 15;

int reading; 
int reading2; 
int nu;

const String com = ",";

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
pinMode(INA, OUTPUT);
pinMode(INB, OUTPUT);
pinMode(INC, OUTPUT);
pinMode(IND, OUTPUT);

pinMode(ledpin, OUTPUT);

pinMode(inPin, INPUT);
pinMode(inPin2, INPUT);

}

void loop() {
  // put your main code here, to run repeatedly:

 reading = analogRead(inPin);
reading2 = analogRead(inPin2);

while(Serial.available() > 0) {
    char c = Serial.read();  //gets one byte from serial buffer
    readString += c; //makes the string readString

    delay(5);  //slow looping to allow buffer to fill with next character
}


if (readString.length() >0) {
    //Serial.println(readString);  //so you can see the captured string 
   //int n = readString.toInt();  //convert readString into a number

   int commaIndex = readString.indexOf(',');
   int secondCommaIndex = readString.indexOf(',', commaIndex+1);

String firstValue = readString.substring(0, commaIndex);
String secondValue = readString.substring(commaIndex+1, secondCommaIndex);
String thirdValue = readString.substring(secondCommaIndex+1); // To the end of the string

int x = firstValue.toInt();
int y = secondValue.toInt();
int z = thirdValue.toInt();

//////////////////////////////////////////////////////////////////////////////////////////////////////////

if (x == 1){

digitalWrite(INA, HIGH);
digitalWrite(INB, LOW);
digitalWrite(INC, LOW);
digitalWrite(IND, LOW);

}

else if (x == 2){


digitalWrite(INA, LOW);
digitalWrite(INB, HIGH);
digitalWrite(INC, LOW);
digitalWrite(IND, LOW);

}

else if (x == 3){


digitalWrite(INC, HIGH);
digitalWrite(IND, LOW);
digitalWrite(INA, LOW);
digitalWrite(INB, LOW);

}

else if (x == 4){


digitalWrite(INC, LOW);
digitalWrite(IND, HIGH);
digitalWrite(INA, LOW);
digitalWrite(INB, LOW);

}


else{

digitalWrite(INA, LOW);
digitalWrite(INB, LOW);
digitalWrite(INC, LOW);
digitalWrite(IND, LOW);


}

Serial.println(1 + com + 2 + com + 3);
//Serial.print(", ");
//Serial.print(reading);
//Serial.print(", ");
//Serial.print(reading2);
//Serial.println(", ");


//////////////////////////////////////////////////////////////////////////////////////////////////////////
}



readString=""; //empty for next input


}

【问题讨论】:

  • 对于您提出的问题,代码太多了。做一个最小的、完整的例子来说明你正在尝试做的事情。

标签: c# string visual-studio split arduino


【解决方案1】:

尝试替换这个:

            int commaIndex = readString.IndexOf(',');
            int secondCommaIndex = readString.IndexOf(',', commaIndex + 1);

            firstValue = readString.Substring(0, commaIndex);
            secondValue = readString.Substring(commaIndex + 1, secondCommaIndex);
            thirdValue = readString.Substring(secondCommaIndex + 1); // To the end of the string

用这个:

            string[] values = readString.Split(new string[]{","},StringSplitOptions.RemoveEmptyEntries);
            firstValue = values[0];
            secondValue = values[1];
            thirdValue = values[2];

希望对你有帮助。

PS - 这假设您始终拥有三个值,就像您在代码中所做的那样。

PPS - 这仅适用于您的 C# 代码。我的理解是,您正在将字符串从 Arduino 发送到 winforms - 只有在 winforms 应用程序中才需要拆分。

【讨论】:

  • 他用的是Arduino,所以没有Split功能。一开始我也是这么想的。
  • 第一段代码似乎是合法的 Windows 窗体应用程序 - 看不到 string.split 是如何工作的。
  • 哦,现在我注意到他在 Arduino 端也有相同的代码。谢谢 - 将尝试清除它。
  • 没问题:)
【解决方案2】:

下次,请不要放所有代码,而只放与您的问题有关的部分。

See this original post for separating the string based on the separator and passing an index to get the value.

String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = { 0, -1 };
int maxIndex = data.length() - 1;

for (int i = 0; i <= maxIndex && found <= index; i++) {
    if (data.charAt(i) == separator || i == maxIndex) {
        found++;
        strIndex[0] = strIndex[1] + 1;
        strIndex[1] = (i == maxIndex) ? i+1 : i;
    }
}
return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}

然后您可以调用传入readString 变量的函数以及您想要的变量的索引:

String firstValue = getValue(readString,',',0);
String secondValue = getValue(readString,',',1);
String thirdValue = getValue(readString,',',2);

【讨论】:

    【解决方案3】:

    试试 String (C#) 中的 Split 方法。如:

         string[] myVars = readString.Split(",");
         if (myVars.Length > 2)
         {
             firstValue = myVars[0];
             secondValue = myVars[1];
             thirdValue = myVars[2];
        }
    

    在调试模式下启动并检查 readString 的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      • 1970-01-01
      相关资源
      最近更新 更多