Reputation: 11
like : Gpu 0x00000100 g0 c670 4h 8w h0 ON h1 -- h2 -- h3 --
I want to check string after h0,h1,h2 and h3 is ON or not
here is my code :
foreach (string line in lines)
{
string find = "h0";
if (line.Contains(find))
{
//int i = line.IndexOf(find);
//string authorName = line.Substring(i, i + );
Console.WriteLine(line);
string[] authorInfo = line.Split(' ');
foreach (string info in authorInfo)
{
int i = 0;
Console.WriteLine(" {0}", info.Substring(info.IndexOf(": ") + 1));
if(info.Substring(info.IndexOf(": ")+1)=="h0")
{
Console.WriteLine(" {0}", info.Substring(info.IndexOf(": ") + 2));
}
}
Upvotes: 1
Views: 98
Reputation: 74605
If you're using a modern c#, you can use String split that takes an array of strings to split on
string x = "Gpu 0x00000100 g0 c670 4h 8w h0 ON h1 -- h2 -- h3 --";
var seps = new[]{" h0 "," h1 "," h2 "," h3 "};
var bits = x.Split(seps, StringSplitOptions.None);
Also with your modern c# you can use the "indices and ranges" feature to easily get the last elements of the array:
var h0 = bits[^4];
var h1 = bits[^3];
var h2 = bits[^2];
var h3 = bits[^1];
Think of the ^
character as being replaced by bits.Length-
, therefore in an array of length 10, bits[^1]
is like bits[bits.Length-1]
ie index 9, the last in the array
If your c# is older and doesn't support this syntax you can still use bits[bits.Length-1]
etc
You could also get the results as another array rather than separate variables, again using ranges
var hs = bits[^4..];
hs
is an array, with the h0
value in hs[0]
and so on
You could use a bit of LINQ for a one liner:
x.Split(seps, StringSplitOptions.None).Reverse().Take(4).Reverse().ToArray()
but it wouldn't be as efficient
Upvotes: 1
Reputation: 1276
You can use a regular expression to find h[0-9] followed by the state (ON or --): (h[0-9]+) ((ON|--))
. This can be done with System.Text.RegularExpressions.Regex:
string line = "Gpu 0x00000100 g0 c670 4h 8w h0 ON h1 -- h2 -- h3 --";
var matches = System.Text.RegularExpressions.Regex.Matches(line, @" (?<variable>h[0-9]+) (?<state>(ON|--))");
foreach (System.Text.RegularExpressions.Match m in matches)
{
Console.WriteLine($"{m.Groups["variable"].Value} is {m.Groups["state"].Value}");
}
Output:
h0 is ON
h1 is --
h2 is --
h3 is --
Upvotes: 4