Getting a part of a string and outputting it to another string - c#

Hi so i'm not exactly sure if the title justifies this question I'm not too good at phrasing sorry.
But what i'm trying to do is um like:
String joggingResults = ",Distance: 2.4km, Duration: 14minutes,";
And ideally, I would like to search joggingResults for " , " and output the words beside it.. and stops when it finds another " , " ... Does this make any sense? haha
My expected result would be something like this but each line is on a new string:
Distance: 2.4km
Duration: 14minutes
I hope someone helps me out tysm

You can split using ',' and then loop through the array and display the results.
var results = joggingResults.Split(',');
foreach(var item in results)
{
Console.WriteLine(item);
}
Note:- Assuming it is a console application. You can display it as per your type of application.

joggingResults.Split(',')
Will give you a collection of strings split where the commas are.

Related

C# IndexOf function not working as expected

So, I'm fairly new to coding, but I've never had a problem with IndexOf until now. I'm trying to search through an html string which looks like:
" data-pid=\"6598160343\">\n\n https://minneapolis.craigslist.org/dak/fuo/d/executive-desk-3-piece-set/6598160343.html\"
class=\"result-image gallery\"
data-ids=\"1:00B0B_hkRi5TEyM9Q,1:00z0z_jTtBxHxlxAZ,1:00p0p_2GU15WOHDEB,1:00909_eKQVd7O1pfE\">\n
$1500\n \n\n \n \n favorite this post\n
\n\n Jun
4\n\n\n https://minneapolis.craigslist.org/dak/fuo/d/executive-desk-3-piece-set/6598160343.html\"
data-id=\"6598160343\" class=\"result-title hdrlnk\">Executive Desk (3
piece set)\n\n\n \n
$1500\n\n\n\n \n pic\n
map\n
\n\n \n hide this posting\n
\n\n \n \n restore\n restore this posting\n
\n\n \n \n\n " string
I'm trying to find the index of specific elements so that I can grab the data later, here's what I have to find the indexes of the positions on either side of the data I want:
DataBookends bkEnds = new DataBookends
{
PIDFrom = (post.IndexOf(#"pid=\""")) + (#"pid=\""".Length),
URLFrom = (post.IndexOf(#"<a href=\")) + (#"<a href=\".Length),
PriceFrom = (post.IndexOf(#"result-price\"">$")) + (#"result-price\"">$".Length),
DateFrom = (post.IndexOf(#"datetime=\""")) + (#"datetime=\""".Length),
TitleFrom = (post.IndexOf(#"result-title hdrlnk\"">")) + (#"result-title hdrlnk\"">".Length),
LocationFrom = (post.IndexOf(#"result-hood\""> (")) + (#"result-hood\""> (".Length)
};
bkEnds.PIDTo = post.IndexOf(#"\""", bkEnds.PIDFrom);
bkEnds.URLTo = post.IndexOf(#"\", bkEnds.URLFrom);
bkEnds.PriceTo = post.IndexOf(#"</span>", bkEnds.PriceFrom);
bkEnds.DateTo = post.IndexOf(#"\", bkEnds.DateFrom);
bkEnds.TitleTo = post.IndexOf(#"</a>", bkEnds.TitleTo);
bkEnds.LocationTo = post.IndexOf(#"\", bkEnds.LocationFrom);
return bkEnds;
However, whenever I try to run it, it either doesn't find anything, or the index values are incorrect. I know I'm missing something simple but I can't figure it out and I feel like a moron. Is it something to do with escape characters I'm not seeing or something with how my string is formatted?
Help please?
EDIT:
I initially tried using the HTML Agility Pack, but I was having trouble understanding how to extract the data I needed so I thought using string.substring() would've been more straightforward.
The index values I'm getting are entirely wrong, even before I tried adding the forward-slashes. I'll be getting rid of those.
I'll write this answer but really it was CraigW in the comments who spotted your error. I think it could still use some explaining as you missed it. Also, the other comments are right that a parser might be the way to go. I still think you should understand the mistake you made as it's generally useful.
You said the variable has this string
" data-pid=\"6598160343\">\n\n https://minneapolis.craigslist.org/dak/fuo/d/executive-desk-3-piece-set/6598160343.html\" class=\"result-image gallery\" data-ids=\"1:00B0B_hkRi5TEyM9Q,1:00z0z_jTtBxHxlxAZ,1:00p0p_2GU15WOHDEB,1:00909_eKQVd7O1pfE\">\n $1500\n \n\n \n \n favorite this post\n
\n\n Jun 4\n\n\n https://minneapolis.craigslist.org/dak/fuo/d/executive-desk-3-piece-set/6598160343.html\" data-id=\"6598160343\" class=\"result-title hdrlnk\">Executive Desk (3 piece set)\n\n\n \n
$1500\n\n\n\n \n pic\n
map\n
\n\n \n hide this posting\n
\n\n \n \n restore\n restore this posting\n
\n\n \n
\n\n " string
which seems to have come from the debugger. You're searching with
post.IndexOf(#"pid=\""")
this won't find a hit, because it is literally looking for pid=\" which is not in your variable. Your variable actually contains
data-pid="6598160343">
https://minneap....
The debugger showed it as
data-pid=\"6598160343\">\n\n https://minneap
because it always 'escapes' quotes (ie a " in the variable shows in the watch window as \") and similarly newlines appear as \n. If you click the magnifying glass icon you will see the string as it really is, without the escapes.
Hope that clears your confusion, if it does you will now realise that this code would work
post.IndexOf(#"pid=""")
Also, for your interest note that if you don't use # before a string then you escape the ", eg.
post.IndexOf("pid=\"")
I think you can change your code a little bit because it's really hard to debug. See my code below and get your idea. You can copy and paste the method ExtractData (and the class as well) to your code, but you need to add some code to verify the patterStart, patterEnd can be found from the content
using System;
public static class StringFinder
{
public static string ExtractData(this string content, string patterStart, string patternEnd)
{
var indexStart = content.IndexOf(patterStart) + patterStart.Length;
var indexEnd = content.IndexOf(patternEnd, indexStart);
return content.Substring(indexStart,indexEnd - indexStart);
}
}
public class Program
{
public static void Main()
{
var data = #" data-pid=\""6598160343\"">\n\n https://minneapolis.craigslist.org/dak/fuo/d/executive-desk-3";
Console.WriteLine(data.ExtractData(#"data-pid=\""", #"\"">"));
}
}
Result 6598160343
So I figured it out, I ended up going with HTML Agility Pack as was suggested by Jeremy. I wasn't able to figure out what exactly was wrong with how I was searching through it with IndexOf and Substring (for example: it would skip "" and continue on until a point that didn't contain any of those characters), but I'm not going to try web-scraping that way again.
For the future, HTML Agility Pack is the way to go!

C# String.Format Characters

Just starting to muddle my way through C# and I have a question which maybe really simple (Once somebody explains it to me).
I have a text box asking for the users National Insurance Number (This is program doesn't do anything it's just me trying to figure out the formatting sequences) - But I'm pulling my hair out trying to work out how to display this back to the label.
at the moment I have the following
string result = String.Format("Thank you, {0}"+
" for your business. You NI # is {1:???}",
nameTextBox.Text,
socialTextBox.Text);
resultLabel.Text = result;
I don't know what to replace the ? with.. Any help would be really appreciated.
Many Thanks
I was looking for something like BN-201285-T
You could make your own function that formats the string to the desired format :
private string CustomFormat(string input) {
return string.Format("BN-{0}-T", input);
}
Then pass the formated string to the string.Format call :
string result = String.Format("Thank you, {0}" +
" for your business. You NI # is {1}",
nameTextBox.Text,
CustomFormat(socialTextBox.Text));
resultLabel.Text = result;

Get data from file and split into an array

I have information formatted on a webpage which looks like the following:
Key=submission_id, Value=300348811884547965
Key=formID, Value=50514289063151
Key=ip, Value=xxxxx
Key=editimage, Value=Yes
Key=openimage5, Value=Yes
Key=copyimage, Value=Yes
How would I go about getting the value of each line, I was thinking of doing some sort of next() while getting all data after the 2nd equal sign of each line however I am unsure on how to do it in c#. I am sure there is a better solution then what I have in mind. Please let me know your thoughts.
A regex works nicely for parsing data structured in this way.
Regex splitter = new Regex(#"Key=([\w]+), Value=([\w]+)");
string path = "TextFile1.txt";
string[] lines = System.IO.File.ReadAllLines(path);
lines.ToList().ForEach((s) =>
{
Match match = splitter.Match(s);
if (match.Success)
{
Console.WriteLine("The Key is " + match.Groups[1] + " and the value is " + match.Groups[2]);
}
});

Populating textbox with contents of Arraylist c#

I have a frustrating problem. With the following code in my clsExchange which is called in my FormExchange with simply txtPhonesInSystem.Text = ClsExchange.listPhones();I can only display the first arraylist entry.
public string listPhones()
{
string strphone = string.Empty;
foreach (clsPhone phone in phoneArray)
{
strphone = (strphone + phone.PhoneNumber.ToString() + "\n");
return strphone;
}
return strphone;
}
However, if i take the logic and put in in the btn_press event on the form.cs it displays the complete contents. The only difference I can see is instead of return strphone I use txtbox.Text=strphone. Any suggestions greatly appreciated aS I have been at this all day.
EDIT
Thankyou all for your answers. I new it had to be something as simple as that. I guess my brain isn't made right for this stuff. Shame because I love it.
This line inside the foreach is the problem:
return strphone;
You're quitting on the first record.
As an aside, is this still C# 1.0? If not, why are you using ArrayLists?
You are calling return in the foreach loop which force to exit entire method at the first loop cycle so strphone contains only the first phome number.
If you are usign .NET 3 you can simplify solution using single LINQ query:
txtPhonesInSystem.Text =
phoneArray.Select(p => p.PhoneNumber)
.Aggregate((acc, next) => acc + "\n" + next);
otherwise just remove return strphone; line of code.
Also it makes sense using Environment.NewLine instead of hard coded "\n" value.

C# : Printing variables and text in a textbox

I need to know the command that I can print a sentence like "the item Peter at row 233 and column 1222 is not a number " .
I far as now I have made this:
string[] lineItems = (string[])List[]
if (!Regex.IsMatch(lineItems[0], (#"^\d*$")))
textBox2.Text += " The number ,lineItems[0], is bigger than
10 " + Environment.NewLine;
I want to print the array fields that have error. So if it finds something it will print it.
I made a code that correctly prints that there is an error on this line of the array, but I cant print the item of the array.
I need to have an Environment.NewLine because I will print many lines.
Thanks ,
George.
foreach (int lineNumber in lineItems)
{
if (lineNumber > 10)
textBox2.Text += "The number " + lineNumber + " is bigger than 10\n";
}
Something like this should work, (I have not checked the c# code, I am working on a mac at the moment)
TextBox2.Text="This is FirstLine\nThis is Second Line";
The code is not compilable absolutely, but I may be understand what you're asking about.
If you are asking about how to compose the string of text box, by adding new strings to it, based on some desicional condition (regex), you can do folowing, pseudocode:
StringBuilder sb = new StringBuidler();
if (!Regex.IsMatch(lineItems[i], (#"^\d*$")))
sb.Append(string.Format(The number ,{0}, is bigger than 10, lineItems[i]) + Environment.NewLine);
textBox2.Text = sb.ToString();
If this is not what you want, just leave the comment, cause it's not very clear from post.
Regards.

Categories