Question:
C# extracting sub string?
Eyla
2009-04-11 22:43:00 UTC
Hi,
I’m trying to extract a substring from a text.
I text my code with a small text and it works with this cod:
String text = null;
String result = null;

text = "%This program implements the backpropagation (BPN) algprithm. It has a general structure, allowing the user to easily modify the" +
"for specific applications by changing parameters without having to recode the main body of the program.";

string start = "backpropagation (BPN)";
string end = "parameters without";

int startIndex = text.IndexOf(start);
int endIndex = text.IndexOf(end);

result = text.Substring(startIndex , endIndex);
MessageBox.Show(result);

Then I tried to download a url sorce code and store it in a string then extract asubstring from that string using this code:
string geturl = null;
string result = null;
String url = "http://www.merriam-webster.com/dictionary/good";

WebClient client = new WebClient();
geturl = client.DownloadString(url);

string start = "";
string end = "
";

int startIndex = geturl.IndexOf(start);
int endIndex = geturl.IndexOf(end);

result = geturl.Substring(startIndex , endIndex);
MessageBox.Show(result);

But I’m getting an error message while the runing time At this line:
result = geturl.Substring(startIndex , endIndex);

error message:
Message="Index and length must refer to a location within the string.\r\nParameter name: length"
I even tried to save the string to a text file then try to extartct but I’m getting same error too.

Please I need help to solve this problem.
Thank you,
Three answers:
George3
2009-04-12 22:52:02 UTC
The second parameter for Substring(x,y) should be a length not an "endIndex".

In other words, "Hi World".Substring(3,5) is "World", not "Wor".



You need to calculate:

int length = endIndex - startIndex + 1;

and do:

result = geturl.Substring(startIndex, length);
2016-04-11 08:55:01 UTC
You've got to define the question more, first. Is the thing you want to assign to x an integer, or a single-digit numeral? Is it always at the end of mystr? What if there are two numerals in mystr (Example: "Math 4 Matic 5") -- what then? A huge part of programming is learning to describe a problem in a way that doesn't allow for misinterpretation. Once you can do that, you can start building a solution that works for any of the possible problems. But you (or your friend?) need to go back to the first step.
2014-04-19 23:35:49 UTC
C# string substring methods......http://csharp.net-informations.com/string/csharp-string-substring.htm


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...