I have the following string:
FB:77:CB:0B:EC:09{W: 0,623413, X: 0,015374, Y: 0,005306, Z: -0,781723}
I want to read out the values of W,X,Y,Z as a float/decimal. The values are not always the same length.
How can I read this string from one character to another without using relative positions?
To read a character in Java, we use next() method followed by charAt(0). The next() method returns the next token/ word in the input as a string and chatAt() method returns the first character in that string. We use the next() and charAt() method in the following way to read a character.
Read a single character. For example, char ch; scanf("%c", &ch); reads one character and stores that character into ch.
In C#, ToCharArray() is a string method. This method is used to copy the characters from a specified string in the current instance to a Unicode character array or the characters of a specified substring in the current instance to a Unicode character array.
I'd suggest matching the "inner" part with a regular expression, but removing the "outer" part manually first - just to keep the regex as simple as possible.
Here's a complete example, with a method that returns the result as a Dictionary<string, string>
. It's not clear how you'd then want to convert the sample values you've given (e.g. "0,623413") into integers, but I'd treat that as a separate task from the initial parsing.
I'm assuming that it's fine to strip all trailing commas from values:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Test
{
static void Main()
{
string input = "FB:77:CB:0B:EC:09{W: 0,623413, X: 0,015374, Y: 0,005306, Z: -0,781723}";
var parsed = Parse(input);
foreach (var entry in parsed)
{
Console.WriteLine($"Key = '{entry.Key}', Value = '{entry.Value}'");
}
}
static readonly Regex regex = new Regex(@"(?<key>[A-Z]+): (?<value>[-\d,]+)");
static IDictionary<string, string> Parse(string input)
{
int openBrace = input.IndexOf('{');
if (openBrace == -1)
{
throw new ArgumentException("Expected input to contain a {");
}
if (!input.EndsWith("}"))
{
throw new ArgumentException("Expected input to end with }");
}
string inner = input.Substring(openBrace + 1, input.Length - openBrace - 2);
var matches = regex.Matches(inner);
return matches.Cast<Match>()
.ToDictionary(match => match.Groups["key"].Value,
match => match.Groups["value"].Value.TrimEnd(','));
}
}
Output:
Key = 'W', Value = '0,623413'
Key = 'X', Value = '0,015374'
Key = 'Y', Value = '0,005306'
Key = 'Z', Value = '-0,781723'
Converting those values to integers may be as simple as removing the commas, trimming leading zeroes, and then using int.Parse
- but it really depends on what you want the results to be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With