Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void Main()
- {
- var response = "B01 S01 D30 S02 D127 P01 D1 B02 S01 DScott\\ Morris S02 D145 P01 D0";
- var boards = new List<Board>();
- var board = (Board)null;
- for (int i = 0; i < response.Length; i++)
- {
- if (response[i] == 'B')
- {
- board = new Board()
- {
- Address = int.Parse(ParseValue(response, ref i))
- };
- boards.Add(board);
- }
- else if(response[i] == 'S' && board != null)
- {
- var sensor = new Sensor()
- {
- Address = int.Parse(ParseValue(response, ref i)),
- Data = (response[++i] == 'D') ? ParseValue(response, ref i) : null
- };
- if(sensor.Data == null) // Correct the position of i for the next value not being data
- i--;
- if (board.Sensors == null)
- board.Sensors = new List<Sensor>();
- board.Sensors.Add(sensor);
- }
- else if(response[i] == 'P' && board != null)
- {
- var peripheral = new Peripheral()
- {
- Address = int.Parse(ParseValue(response, ref i)),
- Data = (response[++i] == 'D') ? ParseValue(response, ref i) : null
- };
- if(peripheral.Data == null) // Correct the position of i for the next value not being data
- i--;
- if (board.Peripherals == null)
- board.Peripherals = new List<Peripheral>();
- board.Peripherals.Add(peripheral);
- }
- }
- boards.Dump();
- }
- public string ParseValue(string response, ref int i) {
- var dataString = string.Empty;
- for (int y = i + 1; y < response.Length; y++)
- {
- if(response[y] == '\\')
- y++;
- //Might have issues with parsing at the beinging (y-1 <= 0).
- if (response[y-1] != '\\' && response[y] == ' ')
- {
- i = y;
- break;
- }
- dataString += response[y];
- }
- return dataString;
- }
- // Define other methods and classes here
- public class Board
- {
- public int Address { get; set; }
- public List<Sensor> Sensors { get; set;}
- public List<Peripheral> Peripherals { get; set; }
- }
- public abstract class Component
- {
- public int Address { get; set; }
- public string Data { get; set; }
- }
- public class Sensor : Component {}
- public class Peripheral : Component {}
- /*
- Pared Output
- |Address |Sensors |Peripherals |
- | 1 ||Address |Data |||Address |Data ||
- | || 1 | 30 ||| 1 | 1 ||
- | || 2 | 127 || |
- |------------------------------------------------------------|
- | 2 ||Address |Data |||Address |Data |
- | || 1 |Scott Morris ||| 1 | 0 ||
- | || 2 |145 || |
- |------------------------------------------------------------|
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement