C# Split function doesn't work - c#

I am trying to split a string made of words, separated by the delimiter "-" and ",". The problem is that my program simply doesn't want to save anything in "var tokens". I already tried making "tokens" a string[], tried to use a char[] separator instead of putting "-" directly in the Split method, and tried the syntax "StringSplitOptions.RemoveEmptyEntries, but nothing works.
Here is my code:
if (!string.IsNullOrEmpty(destin) && string.IsNullOrEmpty(depar))
{
try
{
writer.WriteLine("SearchDest");
writer.WriteLine(destin);
string retur = reader.ReadLine();
Debug.WriteLine(retur);
var tokens = retur.Split('-');
flight.Clear();
foreach (string s in tokens)
{
Debug.WriteLine(s);
String[] flyelem = s.Split(',');
int idf = Convert.ToInt32(flyelem[0]);
String destf = flyelem[1];
String airf = flyelem[2];
int frees = Convert.ToInt32(flyelem[3]);
String datef = flyelem[4];
Flight b = new Flight(idf, destf, airf, frees, datef);
flight.Add(b);
}
dataGridView3.DataSource = null;
dataGridView3.Refresh();
dataGridView3.DataSource = flight;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
The lines
string retur = reader.ReadLine();
Debug.WriteLine(retur);
will print: -6,Moscow,Domodedovo,30,4/3/2017 12:00:00 AM-7,Moscow,Vnukovo,30,4/3/2017 12:00:00 AM-9,Moscow,Vnukovo,40,4/3/2017 12:00:00 AM
and the line "Debug.WriteLine(s);" will always print nothing, just an empty space, the program stopping when it tries to parse the string to int at int idf.
How can I fix this problem and make split to work? Thank you.
EDIT:
Problem fixed. Tommy Naidich suggestion regarding using new[] {'-'} and Gunther Fox one of using StringSplitOptions.RemoveEmptyEntries as the second argument worked, and now the split works as intended. Final code for people who will encounter this problem in the future. Thank you guys.
if (!string.IsNullOrEmpty(destin) && string.IsNullOrEmpty(depar))
{
try
{
writer.WriteLine("SearchDest");
writer.WriteLine(destin);
string retur = reader.ReadLine();
Debug.WriteLine(retur);
string[] output = retur.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
flight.Clear();
foreach (string s in output)
{
Debug.WriteLine(s);
string[] flyelem = s.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int idf = Convert.ToInt32(flyelem[0]);
string destf = flyelem[1];
string airf = flyelem[2];
int frees = Convert.ToInt32(flyelem[3]);
string datef = flyelem[4];
Flight b = new Flight(idf, destf, airf, frees, datef);
flight.Add(b);
}
dataGridView3.DataSource = null;
dataGridView3.Refresh();
dataGridView3.DataSource = flight;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

Use the following syntax and change it to your desire.
string input = "-6,Moscow,Domodedovo,30,4/3/2017 12:00:00 AM-7,Moscow,Vnukovo,30,4/3/2017 12:00:00 AM-9,Moscow,Vnukovo,40,4/3/2017 12:00:00 AM";
string[] output = input.Split(new[] {'-', ','});
foreach(string s in output)
Console.WriteLine(s); // Will print each one of the split words.

Your main issue lies in not checking whether s is empty or not before trying to parse to an int. Adding the additional check before conversions means the loop will properly skip the first element in the array which is blank since your string begins with -.
Also, you were using String instead of string. Please see this answer as to why that's not advised.
You can also use int.TryParse instead of Convert.ToInt32 for some extra error checking.
Working dotnetfiddle
if (!string.IsNullOrEmpty(destin) && string.IsNullOrEmpty(depar))
{
try
{
writer.WriteLine("SearchDest");
writer.WriteLine(destin);
string retur = reader.ReadLine();
Debug.WriteLine(retur);
string[] tokens = retur.Split('-');
flight.Clear();
foreach (string s in tokens)
{
Debug.WriteLine(s);
if (!string.IsNullOrEmpty(s))
{
string[] flyelem = s.Split(',');
int idf;
int frees;
if (int.TryParse(flyelem[0], out idf) &&
int.TryParse(flyelem[3], out frees))
{
string destf = flyelem[1];
string airf = flyelem[2];
string datef = flyelem[4];
Flight b = new Flight(idf, destf, airf, frees, datef);
flight.Add(b);
}
}
}
dataGridView3.DataSource = null;
dataGridView3.Refresh();
dataGridView3.DataSource = flight;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

Related

DateTime parsing in c#:getting a 'System.FormatException: 'String was not recognized as a valid DateTime' error

I have a dataset in a .csv file in a local folder, below is a sample row of the data, it has 13 attributes to each item.
I am parsing this data in C#, my code has been working for 2 years and I cannot remember
The code reading the .csv file is, this section is parsing the data into compiledList.
static string loadFile(string fileLocation)
{
string text = "";
try
{
text = File.ReadAllText(fileLocation);
}
catch (Exception e)
{
Console.WriteLine("An error has occured...");
Console.WriteLine(e.Message);
}
return text;
}
static ConcurrentBag<Item> interpretFile(string text, ConcurrentBag<Item> compiledList)
{
String[] substrings = text.Split('\n');
int settlementPeriod = -1; int totalSP = -1;
foreach (string line in substrings)
{
String[] items = line.Split(',');
if (items[0] == "HDR")
{
settlementPeriod = int.Parse(items[3]);
if (settlementPeriod > 48)
settlementPeriod -= 48;
if (settlementPeriod < 0)
settlementPeriod += 48;
totalSP = getTotalSettlementPeriod(DateTime.ParseExact(items[2], "yyyyMMdd", null), settlementPeriod);
}
if (items[0] == "BOALF")
{
//Item Bid = new Item(items);
Item Bid = new Item
{
recordType = items[0],
unitID = items[1],
acceptID = float.Parse(items[2]),
acceptTime = DateTime.ParseExact(items[3], "yyyyMMddHHmmss", null),
deemedFlag = ToBoolean(items[4]),
soFlag = ToBoolean(items[5]),
storFlag = ToBoolean(items[6]),
fromTime = DateTime.ParseExact(items[7], "yyyyMMddHHmmss", null),
fromLevel = float.Parse(items[8]),
toTime = DateTime.ParseExact(items[9], "yyyyMMddHHmmss", null),
toLevel = float.Parse(items[10]),
settlementPeriod = settlementPeriod,
totalSP = totalSP
};
compiledList.Add(Bid);
Sample item from the .csv is:
When I open the data set in Notebad below is what i see:
Note that items[0] is the first colum from the about sample data set. there the data which I am now having issues with is column 4 which is '2.02E+13' shown above.
What that actually is '20191211202600' which is the 'yyyymmddhhmmss' in number format. I do not know what has changed such that the below is giving me an error.
acceptTime = DateTime.ParseExact(items[3], "yyyyMMddHHmmss", null)
`
The error that I am getting is:
System.FormatException: 'String was not recognized as a valid
DateTime.'
I would appreciate your assistance and let me know if further clarification is required.
Thanks
I don't think the problem is with your C# code, the columns which contain date format yyyymmddhhmmss should be of type string, where they are now treated as a number. This problem arises from the program you are saving the CSV file (for example excel or google spreadsheets) you need to change the column data type to string (as it is now automatically detected as a number).
The following works in .NET fiddle (https://dotnetfiddle.net/), can you verify the string that is being used in the call to DateTime.ParseExact? Perhaps the string is not equal to what you would expect at runtime.
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(DateTime.ParseExact("20191211202600", "yyyyMMddHHmmss", null));
}
}
Output is:
12/11/2019 8:26:00 PM

ambiguity in String startswith the given string

I need to see if string starts with a given string but I am getting ambiguity, here is my code:
string input = "balance1234";
string[] arr = new string[]
{
"bal",
"balance",
};
foreach (string s in arr)
{
if (input.StartsWith(s))
{
var rq= input.Replace(s, "");
}
}
If input is balance1234 , the if condition has to satisfy only with balance, but in my code it is satisfying with bal first.
Here is the solution (using the Hint given by Mr. Skeet):
string input = "balance1234";
string[] arr = new string[]
{
"bal",
"balance",
};
string rq = input;
foreach (string s in arr.OrderByDescending(x => x.Length))
{
if (input.StartsWith(s))
{
rq = input.Replace(s, "");
break;
}
}

Is it possible in C# to return a array back to the calling program?

Is it possible in C# to return a array back to the calling program? If it is not possible, please say it is not all possible. Another alternative is to create a long string and use string.split(). But that does not look nice.
ExamnationOfReturnsFiled("ABCDE1234E") //Calling program.
public yearsfiled[] ExamnationOfReturnsFiled(string panreceived) //function.
{
int k = 0; //to increment the array element.
string item = panreceived; //string value received call program.
string[] yearsfiled = new string[20];//Declaring a string array.
Regex year = new Regex(#"[0-9]{4}-[0-9]{2}");//to capture 2012-13 like entries.
using (StreamReader Reader1 = new StreamReader(#"C: \Users\Unnikrishnan C\Documents\Combined_Blue_Book.txt"))
{
Regex tofindpan = new Regex(item);//Regular Expression to catch the string from the text file being read.
bool tosearch = false;
Regex blank = new Regex(#"^\s*$"); //to detect a blank line.
while ((str.line1 = Reader1.ReadLine()) != null)
{
Match Tofindpan = tofindpan.Match(#"[A-Z]{5}[0-9]{4}[A-Z]{1}");
Match Blank = blank.Match(line1);
if (Blank.Success)
{
tosearch = false;
}
if (Tofindpan.Success)
{
tosearch = true; //when true the
}
if (tosearch == true)
{
Match Year = year.Match(str.line1);
if (Year.Success)
{
yearsfiled[k] = Year.Value;
k++;
}
}
}
return yearsfiled;
}
}
public string[] ExamnationOfReturnsFiled(string panreceived) //function
you are returning type not variable name change the method signature like above
You should be returning a string[]. Your return type yearsfiled[] is a variable name, not a type name
//from calling programme. Tested and succeeded.
string[] yearsfiled = new string[20];
yearsfiled = ExamnationOfReturnsFiled(item1);
// the function name modified as follows.
public static string[] ExamnationOfReturnsFiled(string panreceived)
{
Everything else as in the original post.
}
//It was tested. And found successful. Thanks so much to #Midhun Mundayadan and #Eavidan.

Can't get Regex group value

The string I'm trying to parse from looks something like this:
{"F4q6i9xe":{"Hhgi79M1":"cTZ3W2JG","j0Uszek2":"0"},"a3vSYuq2":{"Kn51uR4Y":"c6QUklQzv+kRLnmvS0zsheqDsRCXbWFVpYhq2rsElKyFQnla01E6P3qQ26b+xWSrscFJCi2qsh6WjJKSW5FN9EwxRAWc3rfyToaEhRngI2WPu3W/b1/hkkS2tEEk7LEpS2ItxLYKjEQGneO5E9rcGzbtfSOikdIjhxpD5m9HsKayo2ZSc2EYd/cN9yfYrNfLOCx+xeGqGcPmmImAzOZM0Q1IXIDQZ5r70vUS1aUOMOFnN1fVxmQ8ISofEKNEpHFfwWW9QUl9eVDgpQ2HES13s20kvVH2FOlE5uahIJBnyTLWYzViAWYyX13VK2PgrQcZ0oLuV84bSbjHGZf+JAjvImuyYhkKDhtTWAGkQ8LZ6r07duo71Gbz3glOUZZyz+FFiH5KrwafBpzGhRlI8El6lLZASN9Z5iZNTKs+sOti1fzsuOBzUXEjFURJGa93GMqPC+OyTw6YxKvgapz7go1XL7EAf50UXpMHd9xAJzsuIb6/lB/6v+XjD70wc74D2OosxtR6DIbQj3gbaBUBABQsJHQZLNnHWqikh+HLCASVbkqw6YPm5NecGaOQxonDkh3ZVQSF15WCEsgNdoWG94OuLF8DSw1t1Kt8sMFkvBJgB7LJS3pAw/Tcg/rvR5qwZ/n31rtOzaJgCdVc6XeIK6Rttj4KvNtgtTwkJIjb97FgIS0CXrR0UCp3BsuLwQg3CRTnjQqsjGgJeinLXX2lq6vNOkxRzgXlWnap96kheYj7sIE/IxbJJWEIInMbH9HU/w0bS0MtIgofpIQAZ/m6XKhu9LpPZBgsBf9KX5chUPeuRfs3MfHFzPYPlCCd2dkE8BHKOTmfS3okqhkzIZvFN3Ni+7enktFdgfpQ0toQbjhpn/TszP34pBaIy77me+GvePNO5bAFECLWSpGvsmW16rLCP0H+xIS/lNf9hK98jQqGU7eqpQdai7WFie2yN75Up7MrgBMp5w9Z5C7qpG2iYGiqynpqTCEnfQ3IZumbL+YvGTiuI2c320MGjKzOdO45MIU5fxUNZQSIfCSyIq5G/XGIeXCG3KETyKDZygXUTgEWbJWNTADE0AhXvP7HMtsuvstyuHvlTZGcfKS4oLnDPFiV1ndIV7+W74Ytv9bAdDIVl36xTzA2PV6waqXBfSPUCTx3jVrAeXcHGFjZtxbk3pFmuqPqgVcxeX/aDbK0NHkR6phQcFEREBjfdCOLAAbCkWiRF0JAA=="}}
And this is my regular expression:
Hhgi79M1":"(?<encodeKeyID>.*?)",.*Kn51uR4Y":"(?<encodedBody>.*?)"}
And this is the code I'm using in my C# application:
string responsePattern = "Hhgi79M1\":\"(?<encodeKeyID>.*?)\",.*Kn51uR4Y\":\"(?<encodedBody>.*?)\"}";
if (Regex.IsMatch(body, responsePattern))
{
var match = Regex.Match(body, responsePattern);
string encodeKeyID = match.Groups["encodeKeyID"].Value;
string encodedBody = match.Groups["encodedBody"].Value;
Now it works, but it doesn't get the value of "encodedBody". I tested my expression with the data on https://regex101.com/ and it seems to work fine on there. However, when getting the value in my program it's just an empty string.
I sense the issue is that your body string is not escaped properly, as your pattern works fine in the following code:
string body = "{\"F4q6i9xe\":{\"Hhgi79M1\":\"cTZ3W2JG\",\"j0Uszek2\":\"0\"},\"a3vSYuq2\":{\"Kn51uR4Y\":\"c6QUklQzv+kRLnmvS0zsheqDsRCXbWFVpYhq2rsElKyFQnla01E6P3qQ26b+xWSrscFJCi2qsh6WjJKSW5FN9EwxRAWc3rfyToaEhRngI2WPu3W/b1/hkkS2tEEk7LEpS2ItxLYKjEQGneO5E9rcGzbtfSOikdIjhxpD5m9HsKayo2ZSc2EYd/cN9yfYrNfLOCx+xeGqGcPmmImAzOZM0Q1IXIDQZ5r70vUS1aUOMOFnN1fVxmQ8ISofEKNEpHFfwWW9QUl9eVDgpQ2HES13s20kvVH2FOlE5uahIJBnyTLWYzViAWYyX13VK2PgrQcZ0oLuV84bSbjHGZf+JAjvImuyYhkKDhtTWAGkQ8LZ6r07duo71Gbz3glOUZZyz+FFiH5KrwafBpzGhRlI8El6lLZASN9Z5iZNTKs+sOti1fzsuOBzUXEjFURJGa93GMqPC+OyTw6YxKvgapz7go1XL7EAf50UXpMHd9xAJzsuIb6/lB/6v+XjD70wc74D2OosxtR6DIbQj3gbaBUBABQsJHQZLNnHWqikh+HLCASVbkqw6YPm5NecGaOQxonDkh3ZVQSF15WCEsgNdoWG94OuLF8DSw1t1Kt8sMFkvBJgB7LJS3pAw/Tcg/rvR5qwZ/n31rtOzaJgCdVc6XeIK6Rttj4KvNtgtTwkJIjb97FgIS0CXrR0UCp3BsuLwQg3CRTnjQqsjGgJeinLXX2lq6vNOkxRzgXlWnap96kheYj7sIE/IxbJJWEIInMbH9HU/w0bS0MtIgofpIQAZ/m6XKhu9LpPZBgsBf9KX5chUPeuRfs3MfHFzPYPlCCd2dkE8BHKOTmfS3okqhkzIZvFN3Ni+7enktFdgfpQ0toQbjhpn/TszP34pBaIy77me+GvePNO5bAFECLWSpGvsmW16rLCP0H+xIS/lNf9hK98jQqGU7eqpQdai7WFie2yN75Up7MrgBMp5w9Z5C7qpG2iYGiqynpqTCEnfQ3IZumbL+YvGTiuI2c320MGjKzOdO45MIU5fxUNZQSIfCSyIq5G/XGIeXCG3KETyKDZygXUTgEWbJWNTADE0AhXvP7HMtsuvstyuHvlTZGcfKS4oLnDPFiV1ndIV7+W74Ytv9bAdDIVl36xTzA2PV6waqXBfSPUCTx3jVrAeXcHGFjZtxbk3pFmuqPqgVcxeX/aDbK0NHkR6phQcFEREBjfdCOLAAbCkWiRF0JAA==\"}}\n" +
"";
string responsePattern = "Hhgi79M1\":\"(?<encodeKeyID>.*?)\",.*Kn51uR4Y\":\"(?<encodedBody>.*?)\"}";
if (Regex.IsMatch(body, responsePattern))
{
var match = Regex.Match(body, responsePattern);
string encodeKeyID = match.Groups["encodeKeyID"].Value;
string encodedBody = match.Groups["encodedBody"].Value;
string msg = String.Format("encodeKeyID: {0}\nencodedBody: {1}", encodeKeyID, encodedBody);
//show in message box
MessageBox.Show(msg, "Pattern Match Result");
}
Output:
Try it this way.
string sTarget = #"
{""F4q6i9xe"":{""Hhgi79M1"":""cTZ3W2JG"",""j0Uszek2"":""0""},""a3vSYuq2"":{""Kn51uR4Y"":""c6QUklQzv+kRLnmvS0zsheqDsRCXbWFVpYhq2rsElKyFQnla01E6P3qQ26b+xWSrscFJCi2qsh6WjJKSW5FN9EwxRAWc3rfyToaEhRngI2WPu3W\/b1\/hkkS2tEEk7LEpS2ItxLYKjEQGneO5E9rcGzbtfSOikdIjhxpD5m9HsKayo2ZSc2EYd\/cN9yfYrNfLOCx+xeGqGcPmmImAzOZM0Q1IXIDQZ5r70vUS1aUOMOFnN1fVxmQ8ISofEKNEpHFfwWW9QUl9eVDgpQ2HES13s20kvVH2FOlE5uahIJBnyTLWYzViAWYyX13VK2PgrQcZ0oLuV84bSbjHGZf+JAjvImuyYhkKDhtTWAGkQ8LZ6r07duo71Gbz3glOUZZyz+FFiH5KrwafBpzGhRlI8El6lLZASN9Z5iZNTKs+sOti1fzsuOBzUXEjFURJGa93GMqPC+OyTw6YxKvgapz7go1XL7EAf50UXpMHd9xAJzsuIb6\/lB\/6v+XjD70wc74D2OosxtR6DIbQj3gbaBUBABQsJHQZLNnHWqikh+HLCASVbkqw6YPm5NecGaOQxonDkh3ZVQSF15WCEsgNdoWG94OuLF8DSw1t1Kt8sMFkvBJgB7LJS3pAw\/Tcg\/rvR5qwZ\/n31rtOzaJgCdVc6XeIK6Rttj4KvNtgtTwkJIjb97FgIS0CXrR0UCp3BsuLwQg3CRTnjQqsjGgJeinLXX2lq6vNOkxRzgXlWnap96kheYj7sIE\/IxbJJWEIInMbH9HU\/w0bS0MtIgofpIQAZ\/m6XKhu9LpPZBgsBf9KX5chUPeuRfs3MfHFzPYPlCCd2dkE8BHKOTmfS3okqhkzIZvFN3Ni+7enktFdgfpQ0toQbjhpn\/TszP34pBaIy77me+GvePNO5bAFECLWSpGvsmW16rLCP0H+xIS\/lNf9hK98jQqGU7eqpQdai7WFie2yN75Up7MrgBMp5w9Z5C7qpG2iYGiqynpqTCEnfQ3IZumbL+YvGTiuI2c320MGjKzOdO45MIU5fxUNZQSIfCSyIq5G\/XGIeXCG3KETyKDZygXUTgEWbJWNTADE0AhXvP7HMtsuvstyuHvlTZGcfKS4oLnDPFiV1ndIV7+W74Ytv9bAdDIVl36xTzA2PV6waqXBfSPUCTx3jVrAeXcHGFjZtxbk3pFmuqPqgVcxeX\/aDbK0NHkR6phQcFEREBjfdCOLAAbCkWiRF0JAA==""}}
";
Regex responseRx = new Regex(#"Hhgi79M1"":""(?<encodeKeyID>.*?)"",.*Kn51uR4Y"":""(?<encodedBody>.*?)""}");
Match responseMatch = responseRx.Match(sTarget);
if (responseMatch.Success)
{
Console.WriteLine("ID = {0}", responseMatch.Groups["encodeKeyID"].Value);
Console.WriteLine("Body = {0}", responseMatch.Groups["encodedBody"].Value);
}
Output
ID = cTZ3W2JG
Body = c6QUklQzv+kRLnmvS0zsheqDsRCXbWFVpYhq2rsElKyFQnla01E6P3qQ26b+xWSrscFJCi2qs
h6WjJKSW5FN9EwxRAWc3rfyToaEhRngI2WPu3W\/b1\/hkkS2tEEk7LEpS2ItxLYKjEQGneO5E9rcGzb
tfSOikdIjhxpD5m9HsKayo2ZSc2EYd\/cN9yfYrNfLOCx+xeGqGcPmmImAzOZM0Q1IXIDQZ5r70vUS1a
UOMOFnN1fVxmQ8ISofEKNEpHFfwWW9QUl9eVDgpQ2HES13s20kvVH2FOlE5uahIJBnyTLWYzViAWYyX1
3VK2PgrQcZ0oLuV84bSbjHGZf+JAjvImuyYhkKDhtTWAGkQ8LZ6r07duo71Gbz3glOUZZyz+FFiH5Krw
afBpzGhRlI8El6lLZASN9Z5iZNTKs+sOti1fzsuOBzUXEjFURJGa93GMqPC+OyTw6YxKvgapz7go1XL7
EAf50UXpMHd9xAJzsuIb6\/lB\/6v+XjD70wc74D2OosxtR6DIbQj3gbaBUBABQsJHQZLNnHWqikh+HL
CASVbkqw6YPm5NecGaOQxonDkh3ZVQSF15WCEsgNdoWG94OuLF8DSw1t1Kt8sMFkvBJgB7LJS3pAw\/T
cg\/rvR5qwZ\/n31rtOzaJgCdVc6XeIK6Rttj4KvNtgtTwkJIjb97FgIS0CXrR0UCp3BsuLwQg3CRTnj
QqsjGgJeinLXX2lq6vNOkxRzgXlWnap96kheYj7sIE\/IxbJJWEIInMbH9HU\/w0bS0MtIgofpIQAZ\/
m6XKhu9LpPZBgsBf9KX5chUPeuRfs3MfHFzPYPlCCd2dkE8BHKOTmfS3okqhkzIZvFN3Ni+7enktFdgf
pQ0toQbjhpn\/TszP34pBaIy77me+GvePNO5bAFECLWSpGvsmW16rLCP0H+xIS\/lNf9hK98jQqGU7eq
pQdai7WFie2yN75Up7MrgBMp5w9Z5C7qpG2iYGiqynpqTCEnfQ3IZumbL+YvGTiuI2c320MGjKzOdO45
MIU5fxUNZQSIfCSyIq5G\/XGIeXCG3KETyKDZygXUTgEWbJWNTADE0AhXvP7HMtsuvstyuHvlTZGcfKS
4oLnDPFiV1ndIV7+W74Ytv9bAdDIVl36xTzA2PV6waqXBfSPUCTx3jVrAeXcHGFjZtxbk3pFmuqPqgVc
xeX\/aDbK0NHkR6phQcFEREBjfdCOLAAbCkWiRF0JAA==

C# String manipulation

I am working on an application that gets text from a text file on a page.
Example link: http://test.com/textfile.txt
This text file contains the following text:
1 Milk Stuff1.rar
2 Milk Stuff2.rar
3 Milk Stuff2-1.rar
4 Union Stuff3.rar
What I am trying to do is as follows, to remove everything from each line, except for "words" that start with 'Stuff' and ends with '.rar'.
The problem is, most of the simple solutions like using .Remove, .Split or .Replace end up failing. This is because, for example, formatting the string using spaces ends up returning this:
1
Milk
Stuff1.rar\n2
Milk
Stuff2.rar\n3
Milk
Stuff2-1.rar\n4
Union
Stuff3.rar\n
I bet it's not as hard as it looks, but I'd apreciate any help you can give me.
Ps: Just to be clear, this is what I want it to return:
Stuff1.rar
Stuff2.rar
Stuff2-1.rar
Stuff3.rar
I am currently working with this code:
client.HeadOnly = true;
string uri = "http://test.com/textfile.txt";
byte[] body = client.DownloadData(uri);
string type = client.ResponseHeaders["content-type"];
client.HeadOnly = false;
if (type.StartsWith(#"text/"))
{
string[] text = client.DownloadString(uri);
foreach (string word in text)
{
if (word.StartsWith("Patch") && word.EndsWith(".rar"))
{
listBox1.Items.Add(word.ToString());
}
}
}
This is obviously not working, but you get the idea.
Thank you in advance!
This should work:
using (var writer = File.CreateText("output.txt"))
{
foreach (string line in File.ReadAllLines("input.txt"))
{
var match = Regex.Match(line, "Stuff.*?\\.rar");
if (match.Success)
writer.WriteLine(match.Value);
}
}
I would be tempted to use a regular expression for this sort of thing.
Something like
Stuff[^\s]*.rar
will pull out just the text you require.
How about a function like:
public static IEnumerable<string> GetStuff(string fileName)
{
var regex = new Regex(#"Stuff[^\s]*.rar");
using (var reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
var match = regex.Match(line);
if (match.Success)
{
yield return match.Value;
}
}
}
}
for(string line in text)
{
if(line.EndsWith(".rar"))
{
int index = line.LastIndexOf("Stuff");
if(index != -1)
{
listBox1.Items.Add(line.Substring(index));
}
}
}

Categories