I am trying to parse data I am getting from an arduino robot I created. I currently have my serial program up and running and I am able to monitor the data being sent and received by my computer.
The data I am trying to get from the robot includes: speed, range, and heading. The data being sent from the arduino are floats.
I use a single character to denote what the data being received is by either a S,R, or H. For example:
R150.6
This would denote that this is range data and 150.6 would be the new range to update the program with.
I'm a little stuck trying to figure out the best way to parse this using c# as this is my first c# program.
I have tried with a similar code to:
if (RxString[0] == 'R')
Range = double.Parse(RxString);
I read on the site to use regular expressions, however I am having a hard time figuring out how to incorporate it into my code.
This is the link I was using for guidance:
String parsing, extracting numbers and letters
You're almost there. If you're always starting with a single letter, try Range = double.Parse(RxString.Substring(1)). It will read from the second character on.
i can use regex for find double:
\d+([,\.]\d+)?
using:
Regex re = Regex.Match("R1.23", "\d+([,\.]\d+)?");
if (re.Success)
{
double #double = Convert.ToDouble(re.Value, System.Globalization.CultureInfo.InvariantCulture);
}
it garanties to get first decimal from string if your letter migrate in string or adding other symbols
Since you know the format of the returned data, you can try something like this
data = RxString.SubString(0,1);
value = RxString.SubString(1, RxString.Length-1);
if(data == "R")
range = double.Parse(value);
Related
I have a program for parsing GS1 Barcodes (with Zebra scanner), which worked just fine, atleast I thought it was OK...
Until I came across one box with 2 GS1 barcodes.. one "linear" and one data matrix (UDI). For linear, it worked just fine, I successfully got out the GTIN and Serial. But datamatrix is different. For some reason, its content is a bit longer than linear code, it has some production date and something else at the end.
This is the Linear code: (01)00380652555852(17)260221(21)25146965079(30)1
This is data matrix: (01)00380652555852(17)260221(21)2514696507911210222240SA60AT225
I have problems with parsing out the Serial number - 25146965079.
Serial number in GS1 has a length of 1-20 characters. This one has 11, but How can I make it stop after the 9 characters? How can I know that the serial ends there?
I tried transforming each character to UDI, but it seems that there is no special separating character or anything.. so I honestly donjt know what to do. Does anyone have any idea?
This the code, if anyone wanna try anything https://prnt.sc/1x2sw8l
Those codes/products came right from the manufacturer, so there shouldnt be anything wrong with the code, I guess...
If you verify the barcode with a scanner that is designed to interpret a GS1 structure, you will see that the generated barcode is in fact incorrect.
You are missing a GS after the serial number, these codes MUST end a variable-length field if it's not the last one. This is specified in GS1 general specifications section 7.8.5.2
Without this separator you can't know where the serial ends - or, a machine interpreting the code can't know.
Tell the manufacturer that they need to study the GS1 specs.
Edit: the "correct" version would be:
(01)00380652555852(17)260221(21)25146965079<GS>(11)210222(240)SA60AT225
The parentheses and group separator <GS> are not included literally in the code.
Since you have two variable-length identifiers (21) and (240) you need a GS no matter what you do. Only alternative would be to have some padding for serial number, then you could do without separator.
According to the GS1 documentation (page 156 and forwards)
All the fields are correct
(01)00380652555852 --> GTIN
(17)260221 --> Expiration date
(21)25146965079 --> Serial Number
(11)210222 --> Production Date
(240)SA60AT225 --> Additional Product Identification
I tried scanning the image but the result was the same as yours.
So the problem is that the separators are not there. Which is a problem for you, and there is no way to know where the serial number ends without the separator.
I am sorry my English is not good
The reason of this problem is group separetors are unreadable character for example if you focus on text box and press capslock button or shift button nothing appear in text box the same in gs
To solve this problem
Public l as integer
And put the following code in keyup event
If textbox1.textlenght = l then
My.combuter.keybord.sendkeys({enter})
L= textbox1.textlenght
End if
This code will give space after each litter (because each litter combined with cabslock button) and five spaces in groub space
store raw input in KeyPress event and then read the character for Letter Or Digit.
if (e.KeyChar != 13)
{
int asci = Convert.ToInt32(e.KeyChar);
if (asci > 31 && asci < 128) // numeric and chars only
rawbcode += Convert.ToChar((int)(e.KeyChar & 0xffff));
else
{
if (asci == 29)
{
rawbcode += "<GS>"; // GS1 Seperator
}
}
}
I would really appreciate your help.
I have a DataGridView where user will be giving us double (2,43 etc).
I want to write a function which can detect if user puts dot in place of comma and just change it itself or treat it as comma for the calculations.
If it was a console app I would just simply write something like
public void ChangeToComma()
{
var someUserInput;
char arr[] = someUserInput.ToCharArray();
for (int i = 0, i < someUserInput.Length; i++)
{
if (char[i] == ".")
{
char[i] = ",";
}
}
}
That would be the logic I would use (maybe not correct but I just wanted to show better what I want to do).
I'm just starting with other than console apps so I'm stuck here :/
What I don't even have a slightest idea about (how to do it) is:
How to go through every single char in a specified DataGridView cell?
How to avoid changing every single dot in every cell of this DataGridView? Some of them are with text so they might contain dots.
You can do it by replacing the comma for a dot using the replace method contained in system
double value = double.Parse(dataGridViewTest.Rows[4].Cells[2].Value.ToString());
dataGridViewTest
.Rows[4]
.Cells[2].Value = value.ToString("N2");
"N2" as a parameter for method to string will set the value as decimal with two digits at the end.
You can also validate the input before saving the data to avoid users insert wrong the information in a wrong format.
I'm currently trying to process a number of data feeds that I have no control over, where I am using Regular Expressions in C# to extract information.
The originator of the data feed is extracting basic row data from their database (like a product name, price, etc), and then formatting that data within rows of English text. For each row, some of the text is repeated static text and some is the dynamically generated text from the database.
e.g
Panasonic TV with FREE Blu-Ray Player
Sony TV with FREE DVD Player + Box Office DVD
Kenwood Hi-Fi Unit with $20 Amazon MP3 Voucher
So the format in this instance is: PRODUCT with FREEGIFT.
PRODUCT and FREEGIFT are dynamic parts of each row, and the "with" text is static. Each feed has about 2000 rows.
Creating a Regular Expression to extract the dynamic parts is trivial.
The problem is that the marketing bods in control of the data feed keep on changing the structure of the static text, usually once a fortnight, so this week I might have:
Brand new Panasonic TV and a FREE Blu-Ray Player if you order today
Brand new Sony TV and a FREE DVD Player + Box Office DVD if you order today
Brand new Kenwood Hi-Fi unit and a $20 Amazon MP3 Voucher if you order today
And next week it will probably be something different, so I have to keep modifying my Regular Expressions...
How would you handle this?
Is there an algorithm to determine static and variable text within repeating rows of strings? If so, what would be the best way to use the output of such an algorithm to programatically create a dynamic Regular Expression?
Thanks for any help or advice.
This code isn't perfect, it certainly isn't efficient, and it's very likely to be too late to help you, but it does work. If given a set of strings, it will return the common content above a certain length.
However, as others have mentioned, an algorithm can only give you an approximation, as you could hit a bad batch where all products have the same initial word, and then the code would accidentally identify that content as static. It may also produce mismatches when dynamic content shares values with static content, but as the size of samples you feed into it grows, the chance of error will shrink.
I'd recommend running this on a subset of your data (20000 rows would be a bad idea!) with some sort of extra sanity checking (max # of static elements etc)
Final caveat: it may do a perfect job, but even if it does, how do you know which item is the PRODUCT and which one is the FREEGIFT?
The algorithm
If all strings in the set start with the same character, add that character to the "current match" set, then remove the leading character from all strings
If not, remove the first character from all strings whose first x (minimum match length) characters aren't contained in all the other strings
As soon as a mismatch is reached (case 2), yield the current match if it meets the length requirement
Continue until all strings are exhausted
The implementation
private static IEnumerable<string> FindCommonContent(string[] strings, int minimumMatchLength)
{
string sharedContent = "";
while (strings.All(x => x.Length > 0))
{
var item1FirstCharacter = strings[0][0];
if (strings.All(x => x[0] == item1FirstCharacter))
{
sharedContent += item1FirstCharacter;
for (int index = 0; index < strings.Length; index++)
strings[index] = strings[index].Substring(1);
continue;
}
if (sharedContent.Length >= minimumMatchLength)
yield return sharedContent;
sharedContent = "";
// If the first minMatch characters of a string aren't in all the other strings, consume the first character of that string
for (int index = 0; index < strings.Length; index++)
{
string testBlock = strings[index].Substring(0, Math.Min(minimumMatchLength, strings[index].Length));
if (!strings.All(x => x.Contains(testBlock)))
strings[index] = strings[index].Substring(1);
}
}
if (sharedContent.Length >= minimumMatchLength)
yield return sharedContent;
}
Output
Set 1 (from your example):
FindCommonContent(strings, 4);
=> "with "
Set 2 (from your example):
FindCommonContent(strings, 4);
=> "Brand new ", "and a ", "if you order today"
Building the regex
This should be as simple as:
"{.*}" + string.Join("{.*}", FindCommonContent(strings, 4)) + "{.*}";
=> "^{.*}Brand new {.*}and a {.*}if you order today{.*}$"
Although you could modify the algorithm to return information about where the matches are (between or outside the static content), this will be fine, as you know some will match zero-length strings anyway.
I think it would be possible with an algorithm , but the time it would take you to code it versus simply doing the Regular Expression might not be worth it.
You could however make your changing process faster. If instead of having your Regex String inside your application, you'd put it in a text file somewhere, you wouldn't have to recompile and redeploy everything every time there's a change, you could simply edit the text file.
Depending on your project size and implementation, this could save you a generous amount of time.
I'm trying to make a calculator-like program where one would enter a calculation in a textbox and it would convert that calculation to an int with the result, here's what I have but it doesn't work much
string calcStr = textBox1.Text;
int result = calcStr;
Any suggestions that aren't too complicated?
If I understand the problem correct you want to be able to parse an expression like 1 + 3 + 4 from a textbox and execute a calculation based on the input. That is actually a harder task than one might think.
One common solution is to use the Shunting-yard algorithm to parse the expression. See http://en.wikipedia.org/wiki/Shunting-yard_algorithm for more details.
Use NCalc for this kind of job... it is free, comes with source and does all the heavy lifting (parse the mathematical expression etc.) and gives you the result of the calculation.
If you're trying to simply parse out the number from a string, use a function like
Int32.Parse(string)
If you need to take out an EQUATION, like
"3+4/2"
then you'll need to extract each character one at a time and determine what it is.
Like if the string was
"32+4/12"
You'd have to loop through every character in the string, and try to parse the current character into a number.
Theres a function to test if it's a number or not. or just check it's ascii value.
if it succeeds, take the current number plus the next one and try again until you hit a non-number character.
Now you can extract your numbers.
Characters that are not numbers are checked against the mathmatical operators you're allowing. Anything else throws an error.
Once you can extract all the whole equation, you'll probably have to do something like Stack operations to evaluate it. I believe in my Assembly class you'd push a buncha numbers and operators to the stack, and then pop it one at a top from the top, evaluating the previous number with the next number by the operator in between.
I hope this is what you were talking about. Best of luck!
i am trying to store large data more than 255 characters in a string datatype but it truncates after 255. how can i achive this basically i need to pass this data to database
C# strings do not have any particular character limit. However the database column you are writing to may have a limit. If you are storing large amounts of data, you should use a BLOB column instead of an ordinary varchar type.
StringBuilder class
Like they said the string class is not limited, but you can do this for large strings. I feel it handles them better.
StringBuilder sb = new StringBuilder();
sb.append("Some text...");
sb.append("more text...");
sb.append("even more text!");
sb.toString();
Okay, it sounds like you have several different technologies involved - Excel, XML, databases etc. Try to tackle just one at a time. First read the data out of Excel, and make sure you can do that without any truncation.
Write a small console app which will read the value, then write it to the console - and its length. If that works, you know the problem isn't in Excel.
Next you can write a small console app with hardcoded input data (so you don't need to keep using interop with Excel) and write the XML from that, or whatever your next stage is.
Basically, take the one big problem ("when I read data from Excel and write it to the database it truncates long values") and split it into smaller and smaller ones until you've found what's wrong.
The string type does not limit strings to 255 characters. Your database column must be 255 characters.
I know that c# strings can hold much longer data than that. If the truncation occurs on commiting to DB, check the length constraint on ur Db field
The problem lies in the Excel part; .Character has a 255 characters limitation.
To read the complete text from a shape the following VBA syntax would do:
Worksheets("YourSheet").Shapes("Shape1").OLEFormat.Object.Text