Saving an integer value after string is found in text file - c#

I've got a program that reads .HRM files and I'm wanting it to search through the text file and retrieve the integer value after whatever it states. I have it reading the text file for other things, I just can't figure this one out. As below for example:
if (line.Contains("Version="))
{
//Get the integer after 'Version='
}
I am not too sure how to get this integer value and store it.
The HRM file reads as below:
[Params]
Version=106
Monitor=34
SMode=111111100
Date=20130205
StartTime=15:46:20.0
Length=01:06:18.9
Interval=1
Upper1=0
Lower1=0
Upper2=0
Lower2=0
Upper3=180
Lower3=170
Timer1=00:00:00.0
Timer2=00:00:00.0

After you find that the line contains Version=
var number = int.Parse(line.Split('=')[1]);

how about
int Version = int.Parse(line.Split('=')[1]);

var versionNumber = int.Parse(line.Replace("Version=", string.Empty));
Or you could do RegEx and so on.

You could use the string methods IndexOf and Substring, for example with this LINQ query:
IEnumerable<String> versions =
from line in File.ReadAllLines(#"filename.HRM") // go through all the lines
let index = line.IndexOf("Version=") // returns -1 if the line doesn't contain "Version="
where index >= 0 // return also those which contain it
select line.Substring(index + "Version=".Length); // return just the version after the '=' sign
foreach (string version in versions)
Console.WriteLine(version);
If you expect only one you could also use string version = versions.FirstOrDefault();
If you want to convert it to int use int.Parse.

If you want to be able to extract just the numbers from any string you would use this:
int versionNumber = int.Parse(Regex.Match(line, #"\d+").Value);

Related

I am trying to extract only numbers from a text file in c#

I am trying to extract only numbers from a text file in c#. My text file is like as below
xasd 50 ysd 20 zaf 40 bhar 60
I am trying to browse a file with openfileDialoug and read that file and extract the numbers from the same file and need to compare those values with a constant value say 60. I need to display how many numbers are present more than that constant number. If those numbers are greater than 60 then i need to append the number of greater values to richtextBox along with the existing text.
You can use the Int32.TryParse(string s,out int result) method. It returns true if the string s can be parsed as an integer and stores the value in int result. Also, you can use the String.Split(Char[]) method to split the line you read from Text File.
string line = fileObject.ReadLine();
int constant = 60; //For your example
int num = 0;
string []tokens = line.Split(); //No arguments in this method means space is used as the delimeter
foreach(string s in tokens)
{
if(Int32.TryParse(s, out num)
{
if(num > constant)
{
//Logic to append to Rich Text Box
}
}
}
Regex is an elegant way to find numbers in a string which is the OP requirement, something like:
string allDetails = File.ReadAllText(Path);
result = Regex.Match(allDetails, #"\d+").Value;
Now the resultString will contain all the extracted integers
In case you want to take care of negative numbers too=, then do this modification
result = Regex.Match(allDetails, #"-?\d+").Value;
Hope this helps, check out the following post:
Find and extract a number from a string
If your file is always like as you have shown then you can easily split it and parse:
string filePath = ""; // from OpenFileDialog
string fileContents = File.ReadAllText(filePath);
string[] values = fileContents.Split();
int valueInt, greaterValuesCount = 0;
foreach (var value in values)
{
if (int.TryParse(value, out valueInt))
{
greaterValueCount++;
// Do something else here
}
}

Grab only part of the string at dynamic location

I have string file with content like this
string a = "12,1,______,_,__;1,23,122;"
I want to grab only this integer value 23. Problem is that this conntent is dynamic and I it's lenght can be changed, so this string a can easily be in the next iteration like
string a = "12,1,______,_,__;11,2,1;"
In this case I would grab integer 2.
If the structure is always the same, then:
Split the string, and grab the element before last.
var array1 = a.Split(';');
// check the array length if it's needed to avoid
// IndexOutOfRangeException exception
var array2 = array1[1].Split(',');
var yourNumber = array2[array2.Length - 2]
String.Split
Ignoring error checking for a minute, this would work:
string a = "12,1,______,_,__;11,2,1;"
int i = Int32.Parse(String.Split(',')[5])
If this is the route you will go, you should take extra care to verify your input. Check the length of the array reutrned from Split, and verify that the 5th value can indeed be parsed to an int.
Try this regex:
(?<=;\d*,)\d*(?=,\d*;)
Sample usage:
class Program
{
static void Main(string[] args)
{
string a = "12,1,______,_,__;1,23,122;";
var regex = new Regex(#"(?<=;\d*,)\d*(?=,\d*;)");
Console.WriteLine(regex.Match(a).Value);
a = "12,1,______,_,__;11,2,1;";
Console.WriteLine(regex.Match(a).Value);
}
}
Try this:
var number = a.split(",")[5];
another option is to split the text into array (if they have same pattern):
var output = a.Split(",;".ToCharArray());
var value = output[theIndex]; // get the index you want

C# Regex.Match to decimal

I have a string "-4.00 %" which I need to convert to a decimal so that I can declare it as a variable and use it later. The string itself is found in string[] rows. My code is as follows:
foreach (string[] row in rows)
{
string row1 = row[0].ToString();
Match rownum = Regex.Match(row1.ToString(), #"\-?\d+\.+?\d+[^%]");
string act = Convert.ToString(rownum); //wouldn't convert match to decimal
decimal actual = Convert.ToDecimal(act);
textBox1.Text = (actual.ToString());
}
This results in "Input string was not in a correct format." Any ideas?
Thanks.
I see two things happening here that could contribute.
You are treating the Regex Match as though you expect it to be a string, but what a Match retrieves is a MatchGroup.
Rather than converting rownum to a string, you need to lookat rownum.Groups[0].
Secondly, you have no parenthesised match to capture. #"(\-?\d+\.+?\d+)%" will create a capture group from the whole lot. This may not matter, I don't know how C# behaves in this circumstance exactly, but if you start stretching your regexes you will want to use bracketed capture groups so you might as well start as you want to go on.
Here's a modified version of your code that changes the regex to use a capturing group and explicitly look for a %. As a consequence, this also simplifies the parsing to decimal (no longer need an intermediary string):
EDIT : check rownum.Success as per executor's suggestion in comments
string[] rows = new [] {"abc -4.01%", "def 6.45%", "monkey" };
foreach (string row in rows)
{
//regex captures number but not %
Match rownum = Regex.Match(row.ToString(), #"(\-?\d+\.+?\d+)%");
//check for match
if(!rownum.Success) continue;
//get value of first (and only) capture
string capture = rownum.Groups[1].Value;
//convert to decimal
decimal actual = decimal.Parse(capture);
//TODO: do something with actual
}
If you're going to use the Match class to handle this, then you have to access the Match.Groups property to get the collection of matches. This class assumes that more than one occurrence appears. If you can guarantee that you'll always get 1 and only 1 you could get it with:
string act = rownum.Groups[0];
Otherwise you'll need to parse through it as in the MSDN documentation.

Remove last characters from a string in C#. An elegant way?

I have a numeric string like this 2223,00. I would like to transform it to 2223. This is: without the information after the ",". Assume that there will be only two decimals after the ",".
I did:
str = str.Remove(str.Length - 3, 3);
Is there a more elegant solution? Maybe using another function? -I donĀ“t like putting explicit numbers-
You can actually just use the Remove overload that takes one parameter:
str = str.Remove(str.Length - 3);
However, if you're trying to avoid hard coding the length, you can use:
str = str.Remove(str.IndexOf(','));
Perhaps this:
str = str.Split(",").First();
This will return to you a string excluding everything after the comma
str = str.Substring(0, str.IndexOf(','));
Of course, this assumes your string actually has a comma with decimals. The above code will fail if it doesn't. You'd want to do more checks:
commaPos = str.IndexOf(',');
if(commaPos != -1)
str = str.Substring(0, commaPos)
I'm assuming you're working with a string to begin with. Ideally, if you're working with a number to begin with, like a float or double, you could just cast it to an int, then do myInt.ToString() like:
myInt = (int)double.Parse(myString)
This parses the double using the current culture (here in the US, we use . for decimal points). However, this again assumes that your input string is can be parsed.
String.Format("{0:0}", 123.4567); // "123"
If your initial value is a decimal into a string, you will need to convert
String.Format("{0:0}", double.Parse("3.5", CultureInfo.InvariantCulture)) //3.5
In this example, I choose Invariant culture but you could use the one you want.
I prefer using the Formatting function because you never know if the decimal may contain 2 or 3 leading number in the future.
Edit: You can also use Truncate to remove all after the , or .
Console.WriteLine(Decimal.Truncate(Convert.ToDecimal("3,5")));
Use:
public static class StringExtensions
{
/// <summary>
/// Cut End. "12".SubstringFromEnd(1) -> "1"
/// </summary>
public static string SubstringFromEnd(this string value, int startindex)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Substring(0, value.Length - startindex);
}
}
I prefer an extension method here for two reasons:
I can chain it with Substring.
Example: f1.Substring(directorypathLength).SubstringFromEnd(1)
Speed.
You could use LastIndexOf and Substring combined to get all characters to the left of the last index of the comma within the sting.
string var = var.Substring(0, var.LastIndexOf(','));
You can use TrimEnd. It's efficient as well and looks clean.
"Name,".TrimEnd(',');
Try the following. It worked for me:
str = str.Split(',').Last();
Since C# 8.0 it has been possible to do this with a range operator.
string textValue = "2223,00";
textValue = textValue[0..^3];
Console.WriteLine(textValue);
This would output the string 2223.
The 0 says that it should start from the zeroth position in the string
The .. says that it should take the range between the operands on either side
The ^ says that it should take the operand relative to the end of the sequence
The 3 says that it should end from the third position in the string
Use lastIndexOf. Like:
string var = var.lastIndexOf(',');

Copy first few strings separated by a symbol in c#

I have a string consist of integer numbers followed by "|" followed by some binary data.
Example.
321654|<some binary data here>
How do i get the numbers in front of the string in the lowest resource usage possible?
i did get the index of the symbol,
string s = "321654654|llasdkjjkwerklsdmv"
int d = s.IndexOf("|");
string n = s.Substring(d + 1).Trim();//did try other trim but unsuccessful
What to do next? Tried copyto but copyto only support char[].
Assuming you only want the numbers before the pipe, you can do:
string n = s.Substring(0, d);
(Make it d + 1 if you want the pipe character to also be included.)
I might be wrong, but I think you are under the impression that the parameter to string.Substring(int) represents "length." It does not; it represents the "start-index" of the desired substring, taken up to the end of the string.
s.Substring(0,d);
You can use String.Split() here is a reference http://msdn.microsoft.com/en-us/library/ms228388%28VS.80%29.aspx
string n = (s.Split("|"))[0] //this gets you the numbers
string o = (s.Split("|"))[1] //this gets you the letters

Categories