/// <summary> /// Parse WITS sentence from string /// </summary> /// <param name="input">String data</param> /// <returns>Return parsed sentence <see cref="WitsSentence"/>/></returns> public static WitsSentence Parse(string input) { try { if (string.IsNullOrEmpty(input)) { throw new Exception("input can't be null null"); } input.Trim(); string[] strWords = input.Split('\n'); if (strWords.Length < INT_MinWordsInSentence) { throw new Exception("WITS sentence has no records"); } if (strWords.First().Trim() != SentenceBegining) { throw new Exception(@"WITS sentence start symbols (&&) not found"); } if (strWords.Where((s) => s == SentenceEnding).FirstOrDefault() == null) { throw new Exception(@"WITS sentence ending not found (!!)"); } var sentence = new WitsSentence(); foreach (var strWord in strWords) { if (strWord.StartsWith(SentenceBegining)) { continue; } if (strWord.StartsWith(SentenceEnding)) { break; } sentence.Records.Add(WitsRecord.Parse(strWord)); } return(sentence); } catch (Exception ex) { throw new ParseException("Error while parsing WITS sentence", ex); } }
/// <summary> /// Deserialize string to <see cref="WitsSentence"/> collection /// </summary> /// <param name="witsData">WITS data string</param> /// <returns>Deserialized wits data of <see cref="WitsSentence"/> collection</returns> public IEnumerable <WitsSentence> StringToSentenceCollection(string witsData) { List <WitsSentence> wSent = new List <WitsSentence>(); int startInd = 0; int stopInd = 0; while (true) { startInd = witsData.IndexOf("&&", stopInd); if (startInd < 0) { break; } stopInd = witsData.IndexOf("!!", startInd); if (stopInd < 0) { break; } wSent.Add(WitsSentence.Parse(witsData.Substring(startInd, stopInd + 2 - startInd))); } return(wSent); }
/// <summary> /// Convert byte array to <see cref="WitsSentence"/> /// </summary> /// <param name="sentenceInBytes">Wits sentence as byte array</param> /// <returns>Returns deserialized WITS sentence</returns> public WitsSentence BytesToSentence(byte[] sentenceInBytes) { return(WitsSentence.Parse(_encoding.GetString(sentenceInBytes))); }
/// <summary> /// Serialize <see cref="WitsSentence"/> to byte array /// </summary> /// <param name="sentence">Wits sentence <see cref="WitsSentence"/></param> /// <returns>Returns byte array</returns> public byte[] SentenceToBytes(WitsSentence sentence) { return(_encoding.GetBytes(sentence.ToString())); }