How to test every value from string array in c#? - c#

Hello I am makimg a firmware check program. And the firmware URL has a bunch of diffrent region URL's. For example AFG TMC EGY. And these all must go at the ending of URL, but I dont want to rewrite the code 3 times. How do I make this into a array and make the app test every of off those region codes.
P.S Im a newbie. I have created the array but further i do not know.
string[] regions = new string[3];
regions[0] = "AFG";
regions[1] = "TMC";
regions[2] = "EGY";

If you are loooking to append the three regions to a url to check against .. you can run the following loop.
string[] regions = new string[3];
regions[0] = "AFG";
regions[1] = "TMC";
regions[2] = "EGY";
foreach(string region in regions)
{
Console.WriteLine($"https://url.com/{region}");
}
// output:
https://url.com/AFG
https://url.com/TMC
https://url.com/EGY
In your code, you would do what you need to do with the URL (instead of simply printing it).

Less code:
var regions = new[] { "AFG", "TMC", "EGY" };
Array.ForEach(regions, r => Console.WriteLine($"https://url.com/{r}"));
...with an attached counter-argument.

Related

Find an array in a string

I am working with the Selenium API in C#.
I try to read a script and get the needed values from that.
string attackable_villages = web.FindElement(By.XPath("//*[#id='content_value']/script[1]")).GetAttribute("innerHTML");
richTextBox1.Text = attackable_villages;
The result I get:
result.scrollBound = {
x_min: 0,
x_max: 999,
y_min: 0,
y_max: 999
};
result.tileSize = [53, 38];
result.screenKey = 'bf14559d';
result.topoKey = 4133874391;
and many more..
But there is this:
result.thisiswhatiwant= [1value1, 1value2, 1value3, 1value4..], [2value1, 2value2, 2value3, ...], [...]
How can I just get that array without the rest and split all elements after "],"
I hope you can help me!
// Split the script in its individual statements
var splitArray = script.Split(';');
// Get the statement you're interested in
var line = splitArray.Where(x => x.Contains("result.thisiswhatiwant")).First();
// Remove all characters except numbers and commas, then split by comma
var values = Regex.Replace(line, "[^0-9,]", string.Empty).Split(',');
Testing with this input:
string script = "test; result.thisiswhatiwant=[1,2,3]; three;";
gives me an array of length 3 (with values 1/2/3 respectively).
You can also use Single(...) instead of Where(...).First() if the statement occurs only once.

Parse Line and Break it into Variables

I have a text file that contain only the FULL version number of an application that I need to extract and then parse it into separate Variables.
For example lets say the version.cs contains 19.1.354.6
Code I'm using does not seem to be working:
char[] delimiter = { '.' };
string currentVersion = System.IO.File.ReadAllText(#"C:\Applicaion\version.cs");
string[] partsVersion;
partsVersion = currentVersion.Split(delimiter);
string majorVersion = partsVersion[0];
string minorVersion = partsVersion[1];
string buildVersion = partsVersion[2];
string revisVersion = partsVersion[3];
Altough your problem is with the file, most likely it contains other text than a version, why dont you use Version class which is absolutely for this kind of tasks.
var version = new Version("19.1.354.6");
var major = version.Major; // etc..
What you have works fine with the correct input, so I would suggest making sure there is nothing else in the file you're reading.
In the future, please provide error information, since we can't usually tell exactly what you expect to happen, only what we know should happen.
In light of that, I would also suggest looking into using Regex for parsing in the future. In my opinion, it provides a much more flexible solution for your needs. Here's an example of regex to use:
var regex = new Regex(#"([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9])");
var match = regex.Match("19.1.354.6");
if (match.Success)
{
Console.WriteLine("Match[1]: "+match.Groups[1].Value);
Console.WriteLine("Match[2]: "+match.Groups[2].Value);
Console.WriteLine("Match[3]: "+match.Groups[3].Value);
Console.WriteLine("Match[4]: "+match.Groups[4].Value);
}
else
{
Console.WriteLine("No match found");
}
which outputs the following:
// Match[1]: 19
// Match[2]: 1
// Match[3]: 354
// Match[4]: 6

How do I Split a string by empty lines?

I want to split my string just by empty entries. I know you can remove these with the string options but in my situation I need them to split the string. Thank you!
string[] text = content.Split(' ');
For example you have this string:
Hi my Name is Max.
I'm 24 years old.
I like programming.
Split the string between old and I.
My Code:
WebClient client = new WebClient();
Stream stream = client.OpenRead("https://gist.githubusercontent.com/Quackmatic/f8deb2b64dd07ea0985d/raw/macbeth.txt");
StreamReader reader = new StreamReader(stream);
string[] text = reader.ReadToEnd().Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < 3; i++)
{
Console.WriteLine(text[i]);
}
Console.ReadLine();
The string is splitted by every new line. The problem is I want to have full paragraphs of my text.
My Output:
string[0] = ACT I.
string[1] = SCENE I. An open place.
string[2] =[An open place. Thunder and lightning. Enter three Witches.]
What I want.
string[0] = ACT I.
string[1] = SCENE I. An open place.
[An open place. Thunder and lightning. Enter three Witches.]
string[2] = FIRST WITCH.
When shall we three meet again
In thunder, lightning, or in rain?
or...
Doubtful it stood;
As two spent swimmers that do cling together
And choke their art. The merciless Macdonwald,
Worthy to be a rebel, for to that
The multiplying villainies of nature
Do swarm upon him, from the Western isles
Of kerns and gallowglasses is supplied;
And fortune, on his damned quarrel smiling,
Show'd like a rebel's whore. But all's too weak;
For brave Macbeth, well he deserves that name,
Disdaining fortune, with his brandish'd steel,
Which smok'd with bloody execution,
Like valour's minion,
Carv'd out his passage, till he fac'd the slave;
And ne'er shook hands, nor bade farewell to him,
Till he unseam'd him from the nave to the chaps,
And fix'd his head upon our battlements
I thought I could get the result by splitting the text by empty lines.
.
var foo = bar.Split(new string[] {Environment.NewLine + Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
It's important to have the combined Environment.NewLine + Environment.NewLine as this will only split when a new line is also followed by a new line (aka a blank line) and split accordingly
The result is:
foo[0] = "Hi my Name is Max.\r\nI'm 24 years old."
foo[1] = "I like programming."
Edit -- Based on your new input try give this a go:
var web = new WebClient();
var stream = web.OpenRead("https://gist.githubusercontent.com/Quackmatic/f8deb2b64dd07ea0985d/raw/macbeth.txt");
if (stream == null) return;
var reader = new StreamReader(stream).ReadToEnd();
var io = reader.Split(new string[] { "\n\n" }, StringSplitOptions.RemoveEmptyEntries);
From here you can iterate through and do what you please (ie. line[i].StartsWith("ACT") to put it into an object if you so wish)
if you are searching for empty lines you should do somthing like
"value".split(environment.newline+environment.newline)

loading CSV data and create array of points

I'm currently tasked with creating a small C# application in Visual C# 2010 Express that loads a CSV file and processes the information to create an array of points, to be displayed on a map.
The entries in the CSV are as follows:
Device;Latitude;Longitude;Speed;Time
57EA7531-0E1F-41C7-B785-22398D445FEA;55.512.653;13.306.292;93;13-4-2014 14:01
The idea is to load this information, split the data, appoint it to different attributes of the following code:
ShapeLayer sl = new ShapeLayer("Marker");
wpfMap.Layers.Add(sl);
marker.Width = marker.Height = 20;
marker.ToolTip = "A map marker"; [needs to contain Device;Latitude;Longitude;Speed;Time]
sl.Shapes.Add(marker);
ShapeCanvas.SetLocation(marker, new System.Windows.Point(8.4, 49)); [needs to contain Longitude,Latitude]
noted inbetween [] is the data from the CSV that needs to be entered.
This CSV file contains about 2000 entries and for each entry, a points needs to be created using the above code. I have very limited experience with loading CSV's and creating an Array with the processed data, is there ayone that can help me out?
There are different ways. I will do something like that.
NOTE. Exception handling will be required in this solution.
string[] allLines = System.IO.File.ReadAllLines(#"yourCVSPath.csv");
foreach(string sLine in allLines)
{
string[] arrLine = sLine.Split(new char[] { ',' }); // or ';' according to provided data
if (arrLine.Length == 5)
{
string sDevice = arrLine[0];
string sLatitude = arrLine[1];
string sLongitude = arrLine[2];
string sSpeed = arrLine[3];
string sTime = arrLine[4];
ShapeLayer sl = new ShapeLayer("Marker");
wpfMap.Layers.Add(sl);
marker.Width = marker.Height = 20;
marker.ToolTip = sLine; //[needs to contain Device;Latitude;Longitude;Speed;Time]
sl.Shapes.Add(marker);
ShapeCanvas.SetLocation(marker, new System.Windows.Point(sLongitude, sLatitude)); //[needs to contain Longitude,Latitude]
}
}

Loop Problem: Assign data to different strings when in a loop

I have a string which consists of different fields. So what I want to do is get the different text and assign each of them into a field.
ex: Hello Allan IBM
so what I want to do is:
put these three words in different strings like
string Greeting = "Hello"
string Name = "Allan"
string Company = "IBM"
//all of it happening in a loop.
string data = "Hello Allan IBM"
string s = data[i].ToString();
string[] words = s.Split(',');
foreach (string word in words) {
Console.WriteLine(word);
}
any suggestions?
thanks hope to hear from you soon
If I understand correctly you have a string with place-holders and you want to put different string in those place-holders:
var format="{0}, {1} {2}. How are you?";
//string Greeting = "Hello"
//string Name = "Allan"
//string Company = "IBM"
//all of it happening in a loop.
string data = ...; //I think you have an array of strings separated by ,
foreach( va s in data){
{
//string s = data[i];//.ToString(); - it is already a string array
string[] words = data[i].Split(',');
Console.WriteLine(format, words[0], words[1], words[2]);
}
To me it sound not like a problem that can be solved with a loop. The essential problem is that the loop can only work if you do exactly the same operation on the items within the loop. If your problem doesn't fit, you end up with a dozen of lines of code within the loop to handle special cases, what could have been written in a shorter way without a loop.
If there are only two or three strings you have to set (what should be the case if you have named variables), assign them from the indexes of the split string. An alternative would be using regular expressions to match some patterns to make it more robust, if one of the expected strings is missing.
Another possibility would be to set attributes on members or properties like:
[MyParseAttribute(/*position*/ /*regex*/)]
string Greeting {get;set;}
And use reflexion to populate them. Here you could create a loop on all properties having that attribute, as it sounds to me that you are eager to create a loop :-)

Categories

Resources